From 82f1c14656f3146ab861d9277023e2d8dc03ed47 Mon Sep 17 00:00:00 2001 From: danielyxie Date: Wed, 6 Jun 2018 11:02:21 -0500 Subject: [PATCH] Added dynamic RAM evaluation to Netscript to prevent exploits by evading RAM usage in NetscriptJS. Calling a HacknetNode API Netscript fn now immediately updates HacknetNodeWrappers --- dist/engine.bundle.js | 52488 ++++++++++++++++++----------------- dist/tests.bundle.js | 52554 ++++++++++++++++++------------------ src/Bladeburner.js | 1 + src/Constants.js | 9 +- src/Crimes.js | 62 +- src/HacknetNode.js | 17 +- src/NetscriptFunctions.js | 883 +- src/NetscriptWorker.js | 6 +- 8 files changed, 52043 insertions(+), 53977 deletions(-) diff --git a/dist/engine.bundle.js b/dist/engine.bundle.js index 721e28856..4c0b7ca85 100644 --- a/dist/engine.bundle.js +++ b/dist/engine.bundle.js @@ -80,27 +80,27 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Player", function() { return Player; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadPlayer", function() { return loadPlayer; }); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Company.js */ 9); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Company.js */ 8); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CompanyManagement.js */ 42); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Crimes.js */ 20); +/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./CompanyManagement.js */ 36); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Crimes.js */ 23); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Gang.js */ 37); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Gang.js */ 33); /* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./SourceFile.js */ 44); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! decimal.js */ 24); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./SourceFile.js */ 37); +/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! decimal.js */ 20); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); /* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20__); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); @@ -1616,56 +1616,21 @@ PlayerObject.prototype.finishCrime = function(cancelled) { var statusText = ""; //TODO, unique message for each crime when you succeed if (Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_6__["determineCrimeSuccess"])(this.crimeType, this.workMoneyGained)) { //Handle Karma and crime statistics - switch(this.crimeType) { - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeShoplift: - this.karma -= 0.1; + let crime = null; + for(const i in _Crimes_js__WEBPACK_IMPORTED_MODULE_6__["Crimes"]) { + if(_Crimes_js__WEBPACK_IMPORTED_MODULE_6__["Crimes"][i].type == this.crimeType) { + crime = _Crimes_js__WEBPACK_IMPORTED_MODULE_6__["Crimes"][i]; break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeRobStore: - this.karma -= 0.5; - this.gainIntelligenceExp(0.25 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeMug: - this.karma -= 0.25; - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeLarceny: - this.karma -= 1.5; - this.gainIntelligenceExp(0.5 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeDrugs: - this.karma -= 0.5; - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeBondForgery: - this.karma -= 0.1; - this.gainIntelligenceExp(2 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeTraffickArms: - this.karma -= 1; - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeHomicide: - ++this.numPeopleKilled; - this.karma -= 3; - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeGrandTheftAuto: - this.karma -= 5; - this.gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeKidnap: - this.karma -= 6; - this.gainIntelligenceExp(2 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeAssassination: - ++this.numPeopleKilled; - this.karma -= 10; - this.gainIntelligenceExp(5 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CrimeHeist: - this.karma -= 15; - this.gainIntelligenceExp(10 * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceCrimeBaseExpGain); - break; - default: - console.log(this.crimeType); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); - return; + } + } + if(crime == null) { + console.log(this.crimeType); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); + } + this.karma -= crime.karma; + this.numPeopleKilled += crime.kills; + if(crime.intelligence_exp > 0) { + this.gainIntelligenceExp(crime.intelligence_exp); } //On a crime success, gain 2x exp @@ -2507,7 +2472,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "exceptionAlert", function() { return exceptionAlert; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createProgressBarText", function() { return createProgressBarText; }); /* harmony import */ var _StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StringHelperFunctions.js */ 2); -/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DialogBox.js */ 7); +/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DialogBox.js */ 6); //General helper functions @@ -2787,7 +2752,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "numNetscriptOperators", function() { return numNetscriptOperators; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHTML", function() { return isHTML; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateRandomString", function() { return generateRandomString; }); -/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DialogBox.js */ 7); +/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DialogBox.js */ 6); //Netburner String helper functions @@ -2964,6 +2929,8 @@ let CONSTANTS = { BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM BaseCostFor1GBOfRamHacknetNode: 30000, + TravelCost: 200000, + BaseCostForHacknetNode: 1000, BaseCostForHacknetNodeCore: 500000, @@ -3434,13 +3401,8 @@ let CONSTANTS = { "World Stock Exchange account and TIX API Access
", LatestUpdate: - "v0.37.2
" + - "* After joining the Bladeburners division, there is now a button to go to the Bladeburner content " + - "in the 'City' page
" + - "* You now start with $250m in BitNode-8 (increased from $100m)
" + - "* Bug Fix: You can now no longer directly edit Hacknet Node values through NetscriptJS (hopefully)
" + - "* Bug Fix: Bladeburners is no longer accessible in BN-8
" + - "* Bug Fix: getBitNodeMultipliers() Netscript function now returns a copy rather than the original object
" + "v0.37.3
" + + "* Bug Fix: Fixed an exploit that allowed calling any Netscript function without incurring any RAM Cost in NetscriptJS
" } @@ -3458,25 +3420,25 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Locations", function() { return Locations; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayLocationContent", function() { return displayLocationContent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initLocationButtons", function() { return initLocationButtons; }); -/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Bladeburner.js */ 27); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company.js */ 9); -/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CompanyManagement.js */ 42); +/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Bladeburner.js */ 40); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company.js */ 8); +/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CompanyManagement.js */ 36); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Crimes.js */ 20); +/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Crimes.js */ 23); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./engine.js */ 5); /* harmony import */ var _Infiltration_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Infiltration.js */ 118); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _ServerPurchases_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ServerPurchases.js */ 84); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _ServerPurchases_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ServerPurchases.js */ 81); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); /* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_15__); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -4520,18 +4482,18 @@ function displayLocationContent() { case Locations.NewTokyoSlums: case Locations.IshimaSlums: case Locations.VolhavenSlums: - var shopliftChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceShoplift"])(); - var robStoreChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceRobStore"])(); - var mugChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceMug"])(); - var larcenyChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceLarceny"])(); - var drugsChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceDealDrugs"])(); - var bondChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceBondForgery"])(); - var armsChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceTraffickArms"])(); - var homicideChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceHomicide"])(); - var gtaChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceGrandTheftAuto"])(); - var kidnapChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceKidnap"])(); - var assassinateChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceAssassination"])(); - var heistChance = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["determineCrimeChanceHeist"])(); + var shopliftChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Shoplift.successRate(); + var robStoreChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].RobStore.successRate(); + var mugChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Mug.successRate(); + var larcenyChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Larceny.successRate(); + var drugsChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].DealDrugs.successRate(); + var bondChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].BondForgery.successRate(); + var armsChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].TraffickArms.successRate(); + var homicideChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Homicide.successRate(); + var gtaChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].GrandTheftAuto.successRate(); + var kidnapChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Kidnap.successRate(); + var assassinateChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Assassination.successRate(); + var heistChance = _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Heist.successRate(); slumsDescText.style.display = "block"; slumsShoplift.style.display = "block"; @@ -5296,92 +5258,92 @@ function initLocationButtons() { }); travelToAevum.addEventListener("click", function() { - travelBoxCreate(Locations.Aevum, 200000); + travelBoxCreate(Locations.Aevum, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); travelToChongqing.addEventListener("click", function() { - travelBoxCreate(Locations.Chongqing, 200000); + travelBoxCreate(Locations.Chongqing, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); travelToSector12.addEventListener("click", function() { - travelBoxCreate(Locations.Sector12, 200000); + travelBoxCreate(Locations.Sector12, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); travelToNewTokyo.addEventListener("click", function() { - travelBoxCreate(Locations.NewTokyo, 200000); + travelBoxCreate(Locations.NewTokyo, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); travelToIshima.addEventListener("click", function() { - travelBoxCreate(Locations.Ishima, 200000); + travelBoxCreate(Locations.Ishima, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); travelToVolhaven.addEventListener("click", function() { - travelBoxCreate(Locations.Volhaven, 200000); + travelBoxCreate(Locations.Volhaven, _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].TravelCost); return false; }); slumsShoplift.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitShopliftCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Shoplift.commit(); return false; }); slumsRobStore.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitRobStoreCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].RobStore.commit(); return false; }); slumsMug.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitMugCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Mug.commit(); return false; }); slumsLarceny.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitLarcenyCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Larceny.commit(); return false; }); slumsDealDrugs.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitDealDrugsCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].DealDrugs.commit(); return false; }); slumsBondForgery.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitBondForgeryCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].BondForgery.commit(); return false; }); slumsTrafficArms.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitTraffickArmsCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].TraffickArms.commit(); return false; }); slumsHomicide.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitHomicideCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Homicide.commit(); return false; }); slumsGta.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitGrandTheftAutoCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].GrandTheftAuto.commit(); return false; }); slumsKidnap.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitKidnapCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Kidnap.commit(); return false; }); slumsAssassinate.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitAssassinationCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Assassination.commit(); return false; }); slumsHeist.addEventListener("click", function() { - Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_4__["commitHeistCrime"])(); + _Crimes_js__WEBPACK_IMPORTED_MODULE_4__["Crimes"].Heist.commit(); return false; }); @@ -5671,44 +5633,44 @@ function purchaseServerBoxCreate(ram, cost) { "use strict"; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; }); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_GameOptions_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/GameOptions.js */ 54); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_GameOptions_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/GameOptions.js */ 50); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); /* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_3__); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/LogBox.js */ 51); -/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 41); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Bladeburner.js */ 27); -/* harmony import */ var _CinematicText_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CinematicText.js */ 70); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Company.js */ 9); -/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./CompanyManagement.js */ 42); +/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/LogBox.js */ 47); +/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Bladeburner.js */ 40); +/* harmony import */ var _CinematicText_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./CinematicText.js */ 66); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Company.js */ 8); +/* harmony import */ var _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./CompanyManagement.js */ 36); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Fconf.js */ 33); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Fconf.js */ 30); /* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Gang.js */ 37); -/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./HacknetNode.js */ 40); -/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25); -/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Literature.js */ 53); -/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Message.js */ 29); -/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Missions.js */ 34); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); +/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Gang.js */ 33); +/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./HacknetNode.js */ 38); +/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 21); +/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Literature.js */ 49); +/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Message.js */ 27); +/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Missions.js */ 39); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Prestige.js */ 57); -/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./RedPill.js */ 45); -/* harmony import */ var _SaveObject_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./SaveObject.js */ 47); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./SourceFile.js */ 44); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./StockMarket.js */ 22); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Terminal.js */ 18); +/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Prestige.js */ 53); +/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./RedPill.js */ 41); +/* harmony import */ var _SaveObject_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./SaveObject.js */ 43); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./SourceFile.js */ 37); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./StockMarket.js */ 29); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Terminal.js */ 15); @@ -7465,973 +7427,10 @@ window.onload = function() { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), /* 6 */ -/*!***********************************!*\ - !*** ./src/NetscriptEvaluator.js ***! - \***********************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeRuntimeRejectMsg", function() { return makeRuntimeRejectMsg; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "netscriptDelay", function() { return netscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptFromScript", function() { return runScriptFromScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingChance", function() { return scriptCalculateHackingChance; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingTime", function() { return scriptCalculateHackingTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateExpGain", function() { return scriptCalculateExpGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculatePercentMoneyHacked", function() { return scriptCalculatePercentMoneyHacked; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateGrowTime", function() { return scriptCalculateGrowTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateWeakenTime", function() { return scriptCalculateWeakenTime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluate", function() { return evaluate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScriptErrorMessage", function() { return isScriptErrorMessage; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killNetscriptDelay", function() { return killNetscriptDelay; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluateImport", function() { return evaluateImport; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 69); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/acorn.js */ 36); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); - - - - - - - - - - - - - - -var Promise = __webpack_require__(/*! bluebird */ 129); - -Promise.config({ - warnings: false, - longStackTraces: false, - cancellation: true, - monitoring: false -}); -/* Evaluator - * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser - * - * Returns a promise - */ -function evaluate(exp, workerScript) { - return Promise.delay(_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (exp == null) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression", exp)); - } - if (env.stopFlag) {return Promise.reject(workerScript);} - switch (exp.type) { - case "BlockStatement": - case "Program": - var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment - return evaluateProgPromise.then(function(w) { - return Promise.resolve(workerScript); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - return Promise.reject(e); - } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - workerScript.errorMessage = e; - return Promise.reject(workerScript); - } else if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { - return Promise.reject(e); - } else { - return Promise.reject(workerScript); - } - }); - break; - case "Literal": - return Promise.resolve(exp.value); - break; - case "Identifier": - //Javascript constructor() method can be used as an exploit to run arbitrary code - if (exp.name == "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - - if (!(exp.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp)); - } - return Promise.resolve(env.get(exp.name)) - break; - case "ExpressionStatement": - return evaluate(exp.expression, workerScript); - break; - case "ArrayExpression": - var argPromises = exp.elements.map(function(arg) { - return evaluate(arg, workerScript); - }); - return Promise.all(argPromises).then(function(array) { - return Promise.resolve(array) - }); - break; - case "CallExpression": - return evaluate(exp.callee, workerScript).then(function(func) { - return Promise.map(exp.arguments, function(arg) { - return evaluate(arg, workerScript); - }).then(function(args) { - if (func instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { //Player-defined function - //Create new Environment for the function - //Should be automatically garbage collected... - var funcEnv = env.extend(); - - //Define function arguments in this new environment - for (var i = 0; i < func.params.length; ++i) { - var arg; - if (i >= args.length) { - arg = null; - } else { - arg = args[i]; - } - funcEnv.def(func.params[i].name, arg); - } - - //Create a new WorkerScript for this function evaluation - var funcWorkerScript = new _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"](workerScript.scriptRef); - funcWorkerScript.serverIp = workerScript.serverIp; - funcWorkerScript.env = funcEnv; - workerScript.fnWorker = funcWorkerScript; - - return evaluate(func.body, funcWorkerScript).then(function(res) { - //If the function finished successfuly, that means there - //was no return statement since a return statement rejects. So resolve to null - workerScript.fnWorker = null; - return Promise.resolve(null); - }).catch(function(e) { - if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { - //Return statement from function - return Promise.resolve(e[1]); - workerScript.fnWorker = null; - } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } else if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { - //Parse out the err message from the WorkerScript and re-reject - var errorMsg = e.errorMessage; - var errorTextArray = errorMsg.split("|"); - if (errorTextArray.length === 4) { - errorMsg = errorTextArray[3]; - return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); - } else { - if (env.stopFlag) { - return Promise.reject(workerScript); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); - } - } - } else if (e instanceof Error) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); - } - }); - } else if (exp.callee.type === "MemberExpression"){ - return evaluate(exp.callee.object, workerScript).then(function(object) { - try { - if (func === "NETSCRIPTFOREACH") { - return evaluateForeach(object, args, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - } - var res = func.apply(object,args); - return Promise.resolve(res); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - }); - } else { - try { - var out = func.apply(null,args); - if (out instanceof Promise){ - return out.then(function(res) { - return Promise.resolve(res) - }).catch(function(e) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - }); - } else { - return Promise.resolve(out); - } - } catch (e) { - if (isScriptErrorMessage(e)) { - if (isScriptErrorMessage(e)) { - //Functions don't have line number appended in error message, so add it - var num = getErrorLineNumber(exp, workerScript); - e += " (Line " + num + ")"; - } - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); - } - } - } - }); - }); - break; - case "MemberExpression": - return evaluate(exp.object, workerScript).then(function(object) { - if (exp.computed){ - return evaluate(exp.property, workerScript).then(function(index) { - if (index >= object.length) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp)); - } - return Promise.resolve(object[index]); - }).catch(function(e) { - if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] || isScriptErrorMessage(e)) { - return Promise.reject(e); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp)); - } - }); - } else { - if (exp.property.name === "constructor") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); - } - if (object != null && object instanceof Array && exp.property.name === "forEach") { - return "NETSCRIPTFOREACH"; - } - try { - return Promise.resolve(object[exp.property.name]) - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp)); - } - } - }); - break; - case "LogicalExpression": - case "BinaryExpression": - return evalBinary(exp, workerScript); - break; - case "UnaryExpression": - return evalUnary(exp, workerScript); - break; - case "AssignmentExpression": - return evalAssignment(exp, workerScript); - break; - case "UpdateExpression": - if (exp.argument.type==="Identifier"){ - if (exp.argument.name in env.vars){ - if (exp.operator === "++" || exp.operator === "--") { - switch (exp.operator) { - case "++": - env.set(exp.argument.name,env.get(exp.argument.name)+1); - break; - case "--": - env.set(exp.argument.name,env.get(exp.argument.name)-1); - break; - default: break; - } - return Promise.resolve(env.get(exp.argument.name)); - } - //Not sure what prefix UpdateExpressions there would be besides ++/-- - if (exp.prefix){ - return Promise.resolve(env.get(exp.argument.name)) - } - switch (exp.operator){ - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp)); - } - return Promise.resolve(env.get(exp.argument.name)) - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp)); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp)); - } - break; - case "EmptyStatement": - return Promise.resolve(false); - break; - case "ReturnStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(["RETURNSTATEMENT", res]); - }); - break; - case "BreakStatement": - return Promise.reject("BREAKSTATEMENT"); - break; - case "ContinueStatement": - return Promise.reject("CONTINUESTATEMENT"); - break; - case "IfStatement": - return evaluateIf(exp, workerScript); - break; - case "SwitchStatement": - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp)); - break; - case "WhileStatement": - return evaluateWhile(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("whileLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "ForStatement": - return evaluate(exp.init, workerScript).then(function(expInit) { - return evaluateFor(exp, workerScript); - }).then(function(forLoopRes) { - return Promise.resolve("forLoopDone"); - }).catch(function(e) { - if (e == "BREAKSTATEMENT" || - (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { - return Promise.resolve("forLoopBroken"); - } else { - return Promise.reject(e); - } - }); - break; - case "FunctionDeclaration": - if (exp.id && exp.id.name) { - env.set(exp.id.name, exp); - return Promise.resolve(true); - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp)); - } - break; - case "ImportDeclaration": - return evaluateImport(exp, workerScript).then(function(res) { - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - break; - case "ThrowStatement": - return evaluate(exp.argument, workerScript).then(function(res) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, res)); - }); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp)); - break; - } //End switch - }).catch(function(e) { - return Promise.reject(e); - }); // End Promise -} - -function evalBinary(exp, workerScript){ - return evaluate(exp.left, workerScript).then(function(expLeft) { - //Short circuiting - if (expLeft == true && exp.operator === "||") { - return Promise.resolve(true); - } - if (expLeft == false && exp.operator === "&&") { - return Promise.resolve(false); - } - return evaluate(exp.right, workerScript).then(function(expRight) { - switch (exp.operator){ - case "===": - case "==": - return Promise.resolve(expLeft===expRight); - break; - case "!==": - case "!=": - return Promise.resolve(expLeft!==expRight); - break; - case "<": - return Promise.resolve(expLeft": - return Promise.resolve(expLeft>expRight); - break; - case ">=": - return Promise.resolve(expLeft>=expRight); - break; - case "+": - return Promise.resolve(expLeft+expRight); - break; - case "-": - return Promise.resolve(expLeft-expRight); - break; - case "*": - return Promise.resolve(expLeft*expRight); - break; - case "/": - if (expRight === 0) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero")); - } else { - return Promise.resolve(expLeft/expRight); - } - break; - case "%": - return Promise.resolve(expLeft%expRight); - break; - case "in": - return Promise.resolve(expLeft in expRight); - break; - case "instanceof": - return Promise.resolve(expLeft instanceof expRight); - break; - case "||": - return Promise.resolve(expLeft || expRight); - break; - case "&&": - return Promise.resolve(expLeft && expRight); - break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator)); - } - }); - }); -} - -function evalUnary(exp, workerScript){ - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return evaluate(exp.argument, workerScript).then(function(res) { - if (exp.operator == "!") { - return Promise.resolve(!res); - } else if (exp.operator == "-") { - if (isNaN(res)) { - return Promise.resolve(res); - } else { - return Promise.resolve(-1 * res); - } - } else { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator)); - } - }); -} - -//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional) -//The return value is an array of the form: -// [0th index (leftmost), array name, 1st index, 2nd index, ...] -function getArrayElement(exp, workerScript) { - var indices = []; - return evaluate(exp.property, workerScript).then(function(idx) { - if (isNaN(idx)) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx)); - } else { - if (exp.object.name === undefined && exp.object.object) { - return getArrayElement(exp.object, workerScript).then(function(res) { - res.push(idx); - indices = res; - return Promise.resolve(indices); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - indices.push(idx); - indices.push(exp.object.name); - return Promise.resolve(indices); - } - } - }); -} - -function evalAssignment(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - - if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left))); - } - - if (exp.operator !== "=" && !(exp.left.name in env.vars)){ - return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined")); - } - - return evaluate(exp.right, workerScript).then(function(expRight) { - if (exp.left.type == "MemberExpression") { - if (!exp.left.computed) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to an object's property. This is currently unsupported in Netscript", exp)); - } - //Assign to array element - //Array object designed by exp.left.object.name - //Index designated by exp.left.property - return getArrayElement(exp.left, workerScript).then(function(res) { - if (!(res instanceof Array) || res.length < 2) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev")); - } - - //The array name is the second value - var arrName = res.splice(1, 1); - arrName = arrName[0]; - - var res; - try { - res = env.setArrayElement(arrName, res, expRight); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); - } - return Promise.resolve(res); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - //Other assignments - try { - var assign; - switch (exp.operator) { - case "=": - assign = expRight; break; - case "+=": - assign = env.get(exp.left.name) + expRight; break; - case "-=": - assign = env.get(exp.left.name) - expRight; break; - case "*=": - assign = env.get(exp.left.name) * expRight; break; - case "/=": - assign = env.get(exp.left.name) / expRight; break; - case "%=": - assign = env.get(exp.left.name) % expRight; break; - default: - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented")); - } - env.set(exp.left.name, assign); - return Promise.resolve(assign); - } catch (e) { - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString())); - } - } - }); -} - -function evaluateIf(exp, workerScript, i) { - var env = workerScript.env; - return evaluate(exp.test, workerScript).then(function(condRes) { - if (condRes) { - return evaluate(exp.consequent, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else if (exp.alternate) { - return evaluate(exp.alternate, workerScript).then(function(res) { - return Promise.resolve(true); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.resolve("endIf"); - } - }); -} - -//Evaluate the looping part of a for loop (Initialization block is NOT done in here) -function evaluateFor(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function(resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).then(function(res) { - return evaluate(exp.update, workerScript); - }).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse to next iteration - return evaluate(exp.update, workerScript).then(function(resPostloop) { - return evaluateFor(exp, workerScript); - }).then(function(foo) { - return Promise.resolve("endForLoop"); - }).catch(function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); -} - -function evaluateForeach(arr, args, workerScript) { - console.log("evaluateForeach called"); - if (!(arr instanceof Array)) { - return Promise.reject("Invalid array passed into forEach"); - } - if (!(args instanceof Array) && args.length != 1) { - return Promise.reject("Invalid argument passed into forEach"); - } - var func = args[0]; - if (typeof func !== "function") { - return Promise.reject("Invalid function passed into forEach"); - } - console.log(func); - return new Promise(function(resolve, reject) { - //Don't return a promise so the promise chain is broken on each recursion - function recurse(i) { - console.log("recurse() called with i: " + i); - if (i >= arr.length) { - resolve(); - } else { - return Promise.delay(_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { - console.log("About to apply function"); - var res = func.apply(null, [arr[i]]); - console.log("Applied function"); - ++i; - Promise.resolve(res).then(function(val) { - recurse(i); - }, reject).catch(function(e) { - return Promise.reject(e); - }); - }); - } - } - recurse(0); - }); -} - -function evaluateWhile(exp, workerScript) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - return new Promise(function (resolve, reject) { - function recurse() { - //Don't return a promise so the promise chain is broken on each recursion (saving memory) - evaluate(exp.test, workerScript).then(function(resCond) { - if (resCond) { - return evaluate(exp.body, workerScript).catch(function(e) { - if (e == "CONTINUESTATEMENT" || - (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "CONTINUESTATEMENT")) { - //Continue statement, recurse - return evaluateWhile(exp, workerScript).then(function(foo) { - return Promise.resolve("endWhileLoop"); - }, function(e) { - return Promise.reject(e); - }); - } else { - return Promise.reject(e); - } - }).then(recurse, reject).catch(function(e) { - return Promise.reject(e); - }); - } else { - resolve(); - } - }).catch(function(e) { - reject(e); - }); - } - recurse(); - }); -} - -function evaluateProg(exp, workerScript, index) { - var env = workerScript.env; - if (env.stopFlag) {return Promise.reject(workerScript);} - if (index >= exp.body.length) { - return Promise.resolve("progFinished"); - } else { - //Evaluate this line of code in the prog - //After the code finishes evaluating, evaluate the next line recursively - return evaluate(exp.body[index], workerScript).then(function(res) { - return evaluateProg(exp, workerScript, index + 1); - }).then(function(res) { - return Promise.resolve(workerScript); - }).catch(function(e) { - return Promise.reject(e); - }); - } -} - -function evaluateImport(exp, workerScript, checkingRam=false) { - //When its checking RAM, it exports an array of nodes for each imported function - var ramCheckRes = []; - - var env = workerScript.env; - if (env.stopFlag) { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(workerScript); - } - - //Get source script and name of all functions to import - var scriptName = exp.source.value; - var namespace, namespaceObj, allFns = false, fnNames = []; - if (exp.specifiers.length === 1 && exp.specifiers[0].type === "ImportNamespaceSpecifier") { - allFns = true; - namespace = exp.specifiers[0].local.name; - } else { - for (var i = 0; i < exp.specifiers.length; ++i) { - fnNames.push(exp.specifiers[i].local.name); - } - } - - //Get the code - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_5__["getServer"])(workerScript.serverIp), code = ""; - if (server == null) { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to identify server. This is a bug please report to dev", exp)); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === scriptName) { - code = server.scripts[i].code; - break; - } - } - if (code === "") { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Could not find script " + scriptName + " to import", exp)); - } - - //Create the AST - try { - var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["parse"])(code, {sourceType:"module"}); - } catch(e) { - console.log("Failed to parse import script"); - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to import functions from " + scriptName + - " This is most likely due to a syntax error in the imported script", exp)); - } - - if (allFns) { - //A namespace is implemented as a JS obj - env.set(namespace, {}); - namespaceObj = env.get(namespace); - } - - //Search through the AST for all imported functions - var queue = [ast]; - while (queue.length != 0) { - var node = queue.shift(); - switch (node.type) { - case "BlockStatement": - case "Program": - for (var i = 0; i < node.body.length; ++i) { - if (node.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { - queue.push(node.body[i]); - } - } - break; - case "FunctionDeclaration": - if (node.id && node.id.name) { - if (allFns) { - //Import all functions under this namespace - if (checkingRam) { - ramCheckRes.push(node); - } else { - namespaceObj[node.id.name] = node; - } - } else { - //Only import specified functions - if (fnNames.includes(node.id.name)) { - if (checkingRam) { - ramCheckRes.push(node); - } else { - env.set(node.id.name, node); - } - - } - } - } else { - if (checkingRam) {return ramCheckRes;} - return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration in imported script " + scriptName, exp)); - } - break; - default: - break; - } - - for (var prop in node) { - if (node.hasOwnProperty(prop)) { - if (node[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { - queue.push(node[prop]); - } - } - } - } - if (!checkingRam) {workerScript.scriptRef.log("Imported functions from " + scriptName);} - if (checkingRam) {return ramCheckRes;} - return Promise.resolve(true); -} - -function killNetscriptDelay(workerScript) { - if (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { - if (workerScript.delay) { - clearTimeout(workerScript.delay); - workerScript.delayResolve(); - } - } -} - -function netscriptDelay(time, workerScript) { - return new Promise(function(resolve, reject) { - workerScript.delay = setTimeout(()=>{ - workerScript.delay = null; - resolve(); - }, time); - workerScript.delayResolve = resolve; - }); -} - -function makeRuntimeRejectMsg(workerScript, msg, exp=null) { - var lineNum = ""; - if (exp != null) { - var num = getErrorLineNumber(exp, workerScript); - lineNum = " (Line " + num + ")" - } - return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg + lineNum; -} - -//Run a script from inside a script using run() command -function runScriptFromScript(server, scriptname, args, workerScript, threads=1) { - //Check if the script is already running - var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_7__["findRunningScript"])(scriptname, args, server); - if (runningScriptObj != null) { - workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname); - return Promise.resolve(false); - } - - //'null/undefined' arguments are not allowed - for (var i = 0; i < args.length; ++i) { - if (args[i] == null) { - workerScript.scriptRef.log("ERROR: Cannot execute a script with null/undefined as an argument"); - return Promise.resolve(false); - } - } - - //Check if the script exists and if it does run it - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - //Check for admin rights and that there is enough RAM availble to run - var script = server.scripts[i]; - var ramUsage = script.ramUsage; - threads = Math.round(Number(threads)); //Convert to number and round - ramUsage = ramUsage * threads * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, threads-1); - var ramAvailable = server.maxRam - server.ramUsed; - - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!"); - return Promise.resolve(false); - } else if (ramUsage > ramAvailable){ - workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!"); - return Promise.resolve(false); - } else { - //Able to run script - workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_9__["printArray"])(args) + ". May take a few seconds to start up..."); - var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_7__["RunningScript"](script, args); - runningScriptObj.threads = threads; - server.runningScripts.push(runningScriptObj); //Push onto runningScripts - Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["addWorkerScript"])(runningScriptObj, server); - return Promise.resolve(true); - } - } - } - workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); - return Promise.resolve(false); -} - -function getErrorLineNumber(exp, workerScript) { - var code = workerScript.scriptRef.scriptRef.code; - - //Split code up to the start of the node - try { - code = code.substring(0, exp.start); - return (code.match(/\n/g) || []).length + 1; - } catch(e) { - return -1; - } -} - -function isScriptErrorMessage(msg) { - if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(msg)) {return false;} - let splitMsg = msg.split("|"); - if (splitMsg.length != 4){ - return false; - } - var ip = splitMsg[1]; - if (!Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_10__["isValidIPAddress"])(ip)) { - return false; - } - return true; -} - -//The same as Player's calculateHackingChance() function but takes in the server as an argument -function scriptCalculateHackingChance(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (1.75 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill) + (0.2 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence); - var skillChance = (skillMult - server.requiredHackingSkill) / skillMult; - var chance = skillChance * difficultyMult * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_chance_mult; - if (chance > 1) {return 1;} - if (chance < 0) {return 0;} - else {return chance;} -} - -//The same as Player's calculateHackingTime() function but takes in the server as an argument -function scriptCalculateHackingTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var hackingTime = 5 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return hackingTime; -} - -//The same as Player's calculateExpGain() function but takes in the server as an argument -function scriptCalculateExpGain(server) { - if (server.baseDifficulty == null) { - server.baseDifficulty = server.hackDifficulty; - } - return (server.baseDifficulty * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_exp_mult * 0.3 + 3) * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain; -} - -//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument -function scriptCalculatePercentMoneyHacked(server) { - var difficultyMult = (100 - server.hackDifficulty) / 100; - var skillMult = (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill - (server.requiredHackingSkill - 1)) / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill; - var percentMoneyHacked = difficultyMult * skillMult * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_money_mult / 240; - if (percentMoneyHacked < 0) {return 0;} - if (percentMoneyHacked > 1) {return 1;} - return percentMoneyHacked * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney; -} - -//Amount of time to execute grow() in milliseconds -function scriptCalculateGrowTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var growTime = 16 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return growTime * 1000; -} - -//Amount of time to execute weaken() in milliseconds -function scriptCalculateWeakenTime(server) { - var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; - var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); - var weakenTime = 20 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds - return weakenTime * 1000; -} - - - - -/***/ }), -/* 7 */ /*!****************************!*\ !*** ./utils/DialogBox.js ***! \****************************/ @@ -8514,10 +7513,10 @@ function dialogBoxCreate(txt, preformatted=false) { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 8 */ +/* 7 */ /*!******************************!*\ !*** ./utils/JSONReviver.js ***! \******************************/ @@ -8602,7 +7601,7 @@ function Generic_fromJSON(ctor, data) { /***/ }), -/* 9 */ +/* 8 */ /*!************************!*\ !*** ./src/Company.js ***! \************************/ @@ -8622,7 +7621,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Location.js */ 4); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); @@ -9772,8 +8771,1337 @@ function getJobRequirementText(company, pos, tooltiptext=false) { +/***/ }), +/* 9 */ +/*!************************!*\ + !*** ./src/Faction.js ***! + \************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextNeurofluxLevel", function() { return getNextNeurofluxLevel; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Factions", function() { return Factions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initFactions", function() { return initFactions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inviteToFaction", function() { return inviteToFaction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinFaction", function() { return joinFaction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayFactionContent", function() { return displayFactionContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processPassiveFactionRepGain", function() { return processPassiveFactionRepGain; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFactions", function() { return loadFactions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Faction", function() { return Faction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentation", function() { return purchaseAugmentation; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factionExists", function() { return factionExists; }); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FactionInfo.js */ 83); +/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Location.js */ 4); +/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Missions.js */ 39); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_FactionInvitationBox_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/FactionInvitationBox.js */ 116); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); + + + + + + + + + + + + + + + + + + +function Faction(name="") { + this.name = name; + this.augmentations = []; //Name of augmentation only + + //Player-related properties for faction + this.isMember = false; //Whether player is member + this.isBanned = false; //Whether or not player is banned from joining this faction + this.playerReputation = 0; //"Reputation" within faction + this.alreadyInvited = false; + + //Faction favor + this.favor = 0; + this.rolloverRep = 0; +}; + +Faction.prototype.getInfo = function() { + const info = _FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfos"][this.name]; + if(info == null) { + throw new Error("Missing faction from FactionInfos: " + this.name+" this probably means the faction got corrupted somehow"); + } + return info; +} + +Faction.prototype.gainFavor = function() { + if (this.favor == null || this.favor == undefined) {this.favor = 0;} + if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} + var res = this.getFavorGain(); + if (res.length != 2) { + console.log("Error: invalid result from getFavorGain() function"); + return; + } + this.favor += res[0]; + this.rolloverRep = res[1]; +} + +//Returns an array with [How much favor would be gained, how much favor would be left over] +Faction.prototype.getFavorGain = function() { + if (this.favor == null || this.favor == undefined) {this.favor = 0;} + if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} + var favorGain = 0, rep = this.playerReputation + this.rolloverRep; + var reqdRep = _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorBase * + Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult, this.favor); + while(rep > 0) { + if (rep >= reqdRep) { + ++favorGain; + rep -= reqdRep; + } else { + break; + } + reqdRep *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult; + } + return [favorGain, rep]; +} + +//Adds all Augmentations to this faction. +Faction.prototype.addAllAugmentations = function() { + this.augmentations.length = 0; + for (var name in _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) { + if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) { + this.augmentations.push(name); + } + } +} + +Faction.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Generic_toJSON"])("Faction", this); +} + +Faction.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Generic_fromJSON"])(Faction, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Reviver"].constructors.Faction = Faction; + +//Map of factions indexed by faction name +let Factions = {} + +function loadFactions(saveString) { + Factions = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Reviver"]); +} + +function AddToFactions(faction) { + var name = faction.name; + Factions[name] = faction; +} + +function factionExists(name) { + return Factions.hasOwnProperty(name); +} + +//TODO Augmentation price and rep requirement mult are 1 for everything right now, +// This might change in the future for balance +function initFactions() { + for(const name in _FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfos"]) { + resetFaction(new Faction(name)); + } +} + +//Resets a faction during (re-)initialization. Saves the favor in the new +//Faction object and deletes the old Faction Object from "Factions". Then +//reinserts the new Faction object +function resetFaction(newFactionObject) { + if (!(newFactionObject instanceof Faction)) { + throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()"); + } + var factionName = newFactionObject.name; + if (factionExists(factionName)) { + newFactionObject.favor = Factions[factionName].favor; + delete Factions[factionName]; + } + AddToFactions(newFactionObject); +} + +function inviteToFaction(faction) { + if (_Settings_js__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressFactionInvites) { + faction.alreadyInvited = true; + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].factionInvitations.push(faction.name); + if (_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Factions) { + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionsContent(); + } + } else { + Object(_utils_FactionInvitationBox_js__WEBPACK_IMPORTED_MODULE_10__["factionInvitationBoxCreate"])(faction); + } +} + +function joinFaction(faction) { + faction.isMember = true; + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].factions.push(faction.name); + const factionInfo = faction.getInfo(); + + //Determine what factions you are banned from now that you have joined this faction + for(const i in factionInfo.enemies) { + const enemy = factionInfo.enemies[i]; + Factions[enemy].isBanned = true; + } +} + +//Displays the HTML content for a specific faction +function displayFactionContent(factionName) { + var faction = Factions[factionName]; + if (faction == null) { + throw new Error("Invalid factionName passed into displayFactionContent: " + factionName); + } + var factionInfo = faction.getInfo(); + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent); + var elements = []; + + //Header and faction info + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", { + innerText:factionName + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { + innerHTML:"" + factionInfo.infoText + "" + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"---------------", + })); + + //Faction reputation and favor + var favorGain = faction.getFavorGain(); + if (favorGain.length != 2) {favorGain = 0;} + favorGain = favorGain[0]; + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText: "Reputation: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(faction.playerReputation, 4), + tooltip:"You will earn " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(favorGain, 4) + + " faction favor upon resetting after installing an Augmentation" + })) + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"---------------", + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Faction Favor: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(faction.favor, 4), + tooltip:"Faction favor increases the rate at which " + + "you earn reputation for this faction by 1% per favor. Faction favor " + + "is gained whenever you reset after installing an Augmentation. The amount of " + + "favor you gain depends on how much reputation you have with the faction" + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"---------------", + })); + + //Faction Work Description Text + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { + id:"faction-work-description-text", + innerText:"Perform work/carry out assignments for your faction to help further its cause! By doing so " + + "you will earn reputation for your faction. You will also gain reputation passively over time, " + + "although at a very slow rate. Earning reputation will allow you to purchase Augmentations " + + "through this faction, which are powerful upgrades that enhance your abilities. Note that you cannot " + + "use your terminal or create scripts when you are performing a task!" + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); + + //Hacking Mission Option + var hackMissionDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-hack-mission-div", class:"faction-work-div", + }); + var hackMissionDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + hackMissionDiv.appendChild(hackMissionDivWrapper); + hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Hacking Mission", + clickListener:()=>{ + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadMissionContent(); + var mission = new _Missions_js__WEBPACK_IMPORTED_MODULE_6__["HackingMission"](faction.playerReputation, faction); + Object(_Missions_js__WEBPACK_IMPORTED_MODULE_6__["setInMission"])(true, mission); //Sets inMission flag to true + mission.init(); + return false; + } + })); + hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Attempt a hacking mission for your faction. " + + "A mission is a mini game that, if won, earns you " + + "significant reputation with this faction. (Recommended hacking level: 200+)" + })); + elements.push(hackMissionDiv); + + //Hacking Contracts Option + var hackDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-hack-div", class:"faction-work-div", + }); + var hackDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + hackDiv.appendChild(hackDivWrapper); + hackDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Hacking Contracts", + clickListener:()=>{ + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionHackWork(faction); + return false; + } + })); + hackDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Complete hacking contracts for your faction. " + + "Your effectiveness, which determines how much " + + "reputation you gain for this faction, is based on your hacking skill. " + + "You will gain hacking exp." + })); + elements.push(hackDiv); + + //Field Work Option + var fieldWorkDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-fieldwork-div", class:"faction-work-div" + }); + var fieldWorkDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + fieldWorkDiv.appendChild(fieldWorkDivWrapper); + fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Field Work", + clickListener:()=>{ + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionFieldWork(faction); + return false; + } + })); + fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Carry out field missions for your faction. " + + "Your effectiveness, which determines how much " + + "reputation you gain for this faction, is based on all of your stats. " + + "You will gain exp for all stats." + })); + elements.push(fieldWorkDiv); + + //Security Work Option + var securityWorkDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-securitywork-div", class:"faction-work-div" + }); + var securityWorkDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + securityWorkDiv.appendChild(securityWorkDivWrapper); + securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Security Work", + clickListener:()=>{ + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionSecurityWork(faction); + return false; + } + })); + securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Serve in a security detail for your faction. " + + "Your effectiveness, which determines how much " + + "reputation you gain for this faction, is based on your combat stats. " + + "You will gain exp for all combat stats." + })); + elements.push(securityWorkDiv); + + //Donate for reputation + var donateDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-donate-div", class:"faction-work-div" + }); + var donateDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + donateDiv.appendChild(donateDivWrapper); + var donateRepGain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"This donation will result in 0 reputation gain" + }); + var donateAmountInput = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", { + placeholder:"Donation amount", + inputListener:()=>{ + var amt = parseFloat(donateAmountInput.value); + if (isNaN(amt) || amt < 0) { + donateRepGain.innerText = "Invalid donate amount entered!"; + } else { + var repGain = amt / 1e6 * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; + donateRepGain.innerText = "This donation will result in " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation gain"; + } + }, + }); + donateDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Donate Money", + clickListener:()=>{ + var amt = parseFloat(donateAmountInput.value); + if (isNaN(amt) || amt < 0) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Invalid amount entered!"); + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.lt(amt)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You cannot afford to donate this much money!"); + } else { + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].loseMoney(amt); + var repGain = amt / 1e6 * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; + faction.playerReputation += repGain; + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You just donated " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(amt).format("$0.000a") + " to " + + faction.name + " to gain " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation"); + displayFactionContent(factionName); + } + } + })); + donateDivWrapper.appendChild(donateAmountInput); + donateDivWrapper.appendChild(donateRepGain); + elements.push(donateDiv); + + //Purchase Augmentations + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { + innerHTML: "
As your reputation with this faction rises, you will " + + "unlock Augmentations, which you can purchase to enhance " + + "your abilities.

" + })); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Purchase Augmentations", + clickListener:()=>{ + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].hideAllContent(); + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.style.display = "block"; + + + displayFactionAugmentations(factionName); + return false; + } + })); + + //Gang (BitNode-2) + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].bitNodeN == 2 && (factionName == "Slum Snakes" || factionName == "Tetrads" || + factionName == "The Syndicate" || factionName == "The Dark Army" || factionName == "Speakers for the Dead" || + factionName == "NiteSec" || factionName == "The Black Hand")) { + //Set everything else to invisible + hackMissionDiv.style.display = "none"; + hackDiv.style.display = "none"; + fieldWorkDiv.style.display = "none"; + securityWorkDiv.style.display = "none"; + donateDiv.style.display = "none"; + + //Create the 'Manage Gang' button + var gangDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { + id:"faction-gang-div", class:"faction-work-div", display:"inline" + }); + var gangDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); + gangDiv.appendChild(gangDivWrapper); + gangDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + class:"a-link-button", innerText:"Manage Gang", + clickListener:()=>{ + if (!_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].inGang()) { + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetNoButton"])(); + yesBtn.innerHTML = "Create Gang"; + noBtn.innerHTML = "Cancel"; + yesBtn.addEventListener("click", () => { + var hacking = false; + if (factionName === "NiteSec" || factionName === "The Black Hand") {hacking = true;} + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startGang(factionName, hacking); + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent(); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); + }); + noBtn.addEventListener("click", () => { + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); + }); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxCreate"])("Would you like to create a new Gang with " + factionName + "?

" + + "Note that this will prevent you from creating a Gang with any other Faction until " + + "this BitNode is destroyed. There are NO differences between the Factions you can " + + "create a Gang with and each of these Factions have all Augmentations available"); + } else { + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent(); + } + } + })); + gangDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + innerText:"Create and manage a gang for this Faction. " + + "Gangs will earn you money and faction reputation." + })); + //Manage Gang button goes before Faction work stuff + elements.splice(7, 1, gangDiv); + + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].inGang() && _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gang.facName != factionName) { + //If the player has a gang but its not for this faction + gangDiv.style.display = "none"; + } + //Display all elements + for (var i = 0; i < elements.length; ++i) { + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]); + } + return; + } + + if (!faction.isMember) { + throw new Error("Not a member of this faction, cannot display faction information"); + } + + donateDiv.style.display = faction.favor >= (150 * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].RepToDonateToFaction) ? "inline" : "none"; + + hackMissionDiv.style.display = factionInfo.offerHackingMission ? "inline": "none"; + hackDiv.style.display = factionInfo.offerHackingWork ? "inline" : "none"; + fieldWorkDiv.style.display = factionInfo.offerFieldWork ? "inline" : "none"; + securityWorkDiv.style.display = factionInfo.offerSecurityWork ? "inline" : "none"; + + //Display all elements + for (var i = 0; i < elements.length; ++i) { + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]); + } +} + +var confirmingPurchases = true; +var sortOption = null; +function displayFactionAugmentations(factionName) { + var faction = Factions[factionName]; + if (faction == null) { + throw new Error("Could not find faction " + factionName + " in displayFactionAugmentations"); + } + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent); + var elements = []; + + //Back button + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + innerText:"Back", class:"a-link-button", + clickListener:()=>{ + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionContent(); + displayFactionContent(factionName); + return false; + } + })); + + //Header text + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", {innerText:"Faction Augmentations"})); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + id:"faction-augmentations-page-desc", + innerHTML:"Lists all Augmentations that are available to purchase from " + factionName + "

" + + "Augmentations are powerful upgrades that will enhance your abilities." + })); + + //Confirming not confirming button + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("label", { + for:"faction-augmentations-confirming-checkbox",innerText:"Confirm Purchases", + color:"white", margin:"4px", padding:"4px", + })); + var confirmingPurchasesCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", { + type:"checkbox", id:"faction-augmentations-confirming-checkbox", checked:confirmingPurchases, + margin:"4px", padding:"4px", + clickListener:()=>{ + confirmingPurchases = confirmingPurchasesCheckbox.checked; + } + }); + elements.push(confirmingPurchasesCheckbox); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); + elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); + + //Augmentations List + var augmentationsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("ul"); + + //Sort buttons + var sortByCostBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + innerText:"Sort by Cost", class:"a-link-button", + clickListener:()=>{ + sortOption = "cost"; + var augs = faction.augmentations.slice(); + augs.sort((augName1, augName2)=>{ + var aug1 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; + if (aug1 == null || aug2 == null) { + throw new Error("Invalid Augmentation Names"); + } + return aug1.baseCost - aug2.baseCost; + }); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); + createFactionAugmentationDisplayElements(augmentationsList, augs, faction); + } + }); + var sortByRepBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + innerText:"Sort by Reputation", class:"a-link-button", + clickListener:()=>{ + sortOption = "reputation"; + var augs = faction.augmentations.slice(); + augs.sort((augName1, augName2)=>{ + var aug1 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; + if (aug1 == null || aug2 == null) { + throw new Error("Invalid Augmentation Names"); + } + return aug1.baseRepRequirement - aug2.baseRepRequirement; + }); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); + createFactionAugmentationDisplayElements(augmentationsList, augs, faction); + } + }); + var defaultSortBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + innerText:"Sort by Default Order", class:"a-link-button", + clickListener:()=>{ + sortOption = "default"; + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); + createFactionAugmentationDisplayElements(augmentationsList, faction.augmentations, faction); + } + }); + elements.push(sortByCostBtn); + elements.push(sortByRepBtn); + elements.push(defaultSortBtn); + switch(sortOption) { + case "cost": + sortByCostBtn.click(); + break; + case "reputation": + sortByRepBtn.click(); + break; + default: + defaultSortBtn.click(); + break; + } + + elements.push(augmentationsList); + + for (var i = 0; i < elements.length; ++i) { + _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.appendChild(elements[i]); + } +} + +//Takes in an array of Augmentation Names, constructs DOM elements +//to list them on the faction page, and appends them to the given +//DOM element +// @augmentationsList DOM List to append Aug DOM elements to +// @augs Array of Aug names +// @faction Faction for which to display Augmentations +function createFactionAugmentationDisplayElements(augmentationsList, augs, faction) { + const factionInfo = faction.getInfo(); + + for (var i = 0; i < augs.length; ++i) { + (function () { + var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augs[i]]; + if (aug == null) { + throw new Error("Invalid Augmentation when trying to create Augmentation display Elements"); + } + var owned = false; + for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++j) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[j].name == aug.name) { + owned = true; + break; + } + } + for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations.length; ++j) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[j].name == aug.name) { + owned = true; + break; + } + } + + var item = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("li"); + var span = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("span", {display:"inline-block"}); + var aDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {tooltip:aug.info}); + var aElem = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { + innerText:aug.name, display:"inline", + clickListener:()=>{ + if (confirmingPurchases) { + purchaseAugmentationBoxCreate(aug, faction); + } else { + purchaseAugmentation(aug, faction); + } + return false; + } + }); + if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { + aElem.innerText += " - Level " + (getNextNeurofluxLevel()); + } + var pElem = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { + display:"inline", + }) + var req = aug.baseRepRequirement * faction.augmentationRepRequirementMult; + var hasPrereqs = hasAugmentationPrereqs(aug); + if (!hasPrereqs) { + aElem.setAttribute("class", "a-link-button-inactive"); + pElem.innerHTML = "LOCKED (Requires " + aug.prereqs.join(",") + " as prerequisite(s))"; + pElem.style.color = "red"; + } else if (aug.name != _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor && (aug.owned || owned)) { + aElem.setAttribute("class", "a-link-button-inactive"); + pElem.innerHTML = "ALREADY OWNED"; + } else if (faction.playerReputation >= req) { + aElem.setAttribute("class", "a-link-button"); + pElem.innerHTML = "UNLOCKED - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * factionInfo.augmentationPriceMult).format("$0.000a"); + } else { + aElem.setAttribute("class", "a-link-button-inactive"); + pElem.innerHTML = "LOCKED (Requires " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(req, 1) + " faction reputation) - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * factionInfo.augmentationPriceMult).format("$0.000a"); + pElem.style.color = "red"; + } + aDiv.appendChild(aElem); + span.appendChild(aDiv); + span.appendChild(pElem); + item.appendChild(span); + augmentationsList.appendChild(item); + }()); //Immediate invocation closure + } +} + +function purchaseAugmentationBoxCreate(aug, fac) { + const factionInfo = fac.info(); + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetNoButton"])(); + yesBtn.innerHTML = "Purchase"; + noBtn.innerHTML = "Cancel"; + yesBtn.addEventListener("click", function() { + purchaseAugmentation(aug, fac); + }); + noBtn.addEventListener("click", function() { + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); + }); + + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxCreate"])("

" + aug.name + "


" + + aug.info + "

" + + "
Would you like to purchase the " + aug.name + " Augmentation for $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(aug.baseCost * factionInfo.augmentationPriceMult, 2) + "?"); +} + +//Returns a boolean indicating whether the player has the prerequisites for the +//specified Augmentation +function hasAugmentationPrereqs(aug) { + var hasPrereqs = true; + if (aug.prereqs && aug.prereqs.length > 0) { + for (var i = 0; i < aug.prereqs.length; ++i) { + var prereqAug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][aug.prereqs[i]]; + if (prereqAug == null) { + console.log("ERROR: Invalid prereq Augmentation: " + aug.prereqs[i]); + continue; + } + if (prereqAug.owned === false) { + hasPrereqs = false; + + //Check if the aug is purchased + for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++j) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[j].name === prereqAug.name) { + hasPrereqs = true; + break; + } + } + } + } + } + return hasPrereqs; +} + +function purchaseAugmentation(aug, fac, sing=false) { + var hasPrereqs = hasAugmentationPrereqs(aug); + if (!hasPrereqs) { + var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + + "purchase this one."; + if (sing) {return txt;} else {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt);} + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.lt(aug.baseCost * fac.augmentationPriceMult)) { + let txt = "You don't have enough money to purchase " + aug.name; + if (sing) {return txt;} + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt); + } else if (fac.playerReputation < aug.baseRepRequirement) { + let txt = "You don't have enough faction reputation to purchase " + aug.name; + if (sing) {return txt;} + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt); + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.gte(aug.baseCost * fac.augmentationPriceMult)) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].firstAugPurchased === false) { + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].firstAugPurchased = true; + document.getElementById("augmentations-tab").style.display = "list-item"; + document.getElementById("character-menu-header").click(); + document.getElementById("character-menu-header").click(); + } + + var queuedAugmentation = new _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["PlayerOwnedAugmentation"](aug.name); + if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { + queuedAugmentation.level = getNextNeurofluxLevel(); + } + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.push(queuedAugmentation); + + _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].loseMoney((aug.baseCost * fac.augmentationPriceMult)); + + //If you just purchased Neuroflux Governor, recalculate the cost + if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { + var nextLevel = getNextNeurofluxLevel(); + --nextLevel; + var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel); + aug.baseRepRequirement = 500 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationRepCost; + aug.baseCost = 750e3 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationMoneyCost; + + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length-1; ++i) { + aug.baseCost *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier; + } + } + + for (var name in _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) { + if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) { + _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][name].baseCost *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier; + } + } + + if (sing) { + return "You purchased " + aug.name; + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You purchased " + aug.name + ". It's enhancements will not take " + + "effect until they are installed. To install your augmentations, go to the " + + "'Augmentations' tab on the left-hand navigation menu. Purchasing additional " + + "augmentations will now be more expensive."); + } + + displayFactionAugmentations(fac.name); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Hmm, something went wrong when trying to purchase an Augmentation. " + + "Please report this to the game developer with an explanation of how to " + + "reproduce this."); + } + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); +} + +function getNextNeurofluxLevel() { + var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor]; + if (aug == null) { + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations.length; ++i) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[i].name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { + aug = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[i]; + } + } + if (aug == null) { + console.log("WARNING: Could not find NeuroFlux Governor aug. This is OK if " + + "it happens during the loading/initialization of the game, but probably " + + "indicates something seriously wrong at other times"); + return 1; + } + } + var nextLevel = aug.level + 1; + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++i) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[i].name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { + ++nextLevel; + } + } + return nextLevel; +} + +function processPassiveFactionRepGain(numCycles) { + var numTimesGain = (numCycles / 600) * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; + for (var name in Factions) { + if (Factions.hasOwnProperty(name)) { + var faction = Factions[name]; + + //TODO Get hard value of 1 rep per "rep gain cycle"" for now.. + //maybe later make this based on + //a player's 'status' like how powerful they are and how much money they have + if (faction.isMember) {faction.playerReputation += (numTimesGain * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionPassiveRepGain);} + } + } +} + + + + /***/ }), /* 10 */ +/*!*************************************************!*\ + !*** ./node_modules/numeral/min/numeral.min.js ***! + \*************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @preserve + * numeral.js + * version : 2.0.6 + * author : Adam Draper + * license : MIT + * http://adamwdraper.github.com/Numeral-js/ + */ +!function(a,b){ true?!(__WEBPACK_AMD_DEFINE_FACTORY__ = (b), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):undefined}(this,function(){function a(a,b){this._input=a,this._value=b}var b,c,d="2.0.6",e={},f={},g={currentLocale:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0",scalePercentBy100:!0},h={currentLocale:g.currentLocale,zeroFormat:g.zeroFormat,nullFormat:g.nullFormat,defaultFormat:g.defaultFormat,scalePercentBy100:g.scalePercentBy100};return b=function(d){var f,g,i,j;if(b.isNumeral(d))f=d.value();else if(0===d||"undefined"==typeof d)f=0;else if(null===d||c.isNaN(d))f=null;else if("string"==typeof d)if(h.zeroFormat&&d===h.zeroFormat)f=0;else if(h.nullFormat&&d===h.nullFormat||!d.replace(/[^0-9]+/g,"").length)f=null;else{for(g in e)if(j="function"==typeof e[g].regexps.unformat?e[g].regexps.unformat():e[g].regexps.unformat,j&&d.match(j)){i=e[g].unformat;break}i=i||b._.stringToNumber,f=i(d)}else f=Number(d)||null;return new a(d,f)},b.version=d,b.isNumeral=function(b){return b instanceof a},b._=c={numberToFormat:function(a,c,d){var e,g,h,i,j,k,l,m=f[b.options.currentLocale],n=!1,o=!1,p=0,q="",r=1e12,s=1e9,t=1e6,u=1e3,v="",w=!1;if(a=a||0,g=Math.abs(a),b._.includes(c,"(")?(n=!0,c=c.replace(/[\(|\)]/g,"")):(b._.includes(c,"+")||b._.includes(c,"-"))&&(j=b._.includes(c,"+")?c.indexOf("+"):0>a?c.indexOf("-"):-1,c=c.replace(/[\+|\-]/g,"")),b._.includes(c,"a")&&(e=c.match(/a(k|m|b|t)?/),e=e?e[1]:!1,b._.includes(c," a")&&(q=" "),c=c.replace(new RegExp(q+"a[kmbt]?"),""),g>=r&&!e||"t"===e?(q+=m.abbreviations.trillion,a/=r):r>g&&g>=s&&!e||"b"===e?(q+=m.abbreviations.billion,a/=s):s>g&&g>=t&&!e||"m"===e?(q+=m.abbreviations.million,a/=t):(t>g&&g>=u&&!e||"k"===e)&&(q+=m.abbreviations.thousand,a/=u)),b._.includes(c,"[.]")&&(o=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],k=c.indexOf(","),p=(c.split(".")[0].split(",")[0].match(/0/g)||[]).length,i?(b._.includes(i,"[")?(i=i.replace("]",""),i=i.split("["),v=b._.toFixed(a,i[0].length+i[1].length,d,i[1].length)):v=b._.toFixed(a,i.length,d),h=v.split(".")[0],v=b._.includes(v,".")?m.delimiters.decimal+v.split(".")[1]:"",o&&0===Number(v.slice(1))&&(v="")):h=b._.toFixed(a,0,d),q&&!e&&Number(h)>=1e3&&q!==m.abbreviations.trillion)switch(h=String(Number(h)/1e3),q){case m.abbreviations.thousand:q=m.abbreviations.million;break;case m.abbreviations.million:q=m.abbreviations.billion;break;case m.abbreviations.billion:q=m.abbreviations.trillion}if(b._.includes(h,"-")&&(h=h.slice(1),w=!0),h.length0;x--)h="0"+h;return k>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+m.delimiters.thousands)),0===c.indexOf(".")&&(h=""),l=h+v+(q?q:""),n?l=(n&&w?"(":"")+l+(n&&w?")":""):j>=0?l=0===j?(w?"-":"+")+l:l+(w?"-":"+"):w&&(l="-"+l),l},stringToNumber:function(a){var b,c,d,e=f[h.currentLocale],g=a,i={thousand:3,million:6,billion:9,trillion:12};if(h.zeroFormat&&a===h.zeroFormat)c=0;else if(h.nullFormat&&a===h.nullFormat||!a.replace(/[^0-9]+/g,"").length)c=null;else{c=1,"."!==e.delimiters.decimal&&(a=a.replace(/\./g,"").replace(e.delimiters.decimal,"."));for(b in i)if(d=new RegExp("[^a-zA-Z]"+e.abbreviations[b]+"(?:\\)|(\\"+e.currency.symbol+")?(?:\\))?)?$"),g.match(d)){c*=Math.pow(10,i[b]);break}c*=(a.split("-").length+Math.min(a.split("(").length-1,a.split(")").length-1))%2?1:-1,a=a.replace(/[^0-9\.]+/g,""),c*=Number(a)}return c},isNaN:function(a){return"number"==typeof a&&isNaN(a)},includes:function(a,b){return-1!==a.indexOf(b)},insert:function(a,b,c){return a.slice(0,c)+b+a.slice(c)},reduce:function(a,b){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof b)throw new TypeError(b+" is not a function");var c,d=Object(a),e=d.length>>>0,f=0;if(3===arguments.length)c=arguments[2];else{for(;e>f&&!(f in d);)f++;if(f>=e)throw new TypeError("Reduce of empty array with no initial value");c=d[f++]}for(;e>f;f++)f in d&&(c=b(c,d[f],f,d));return c},multiplier:function(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)},correctionFactor:function(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var d=c.multiplier(b);return a>d?a:d},1)},toFixed:function(a,b,c,d){var e,f,g,h,i=a.toString().split("."),j=b-(d||0);return e=2===i.length?Math.min(Math.max(i[1].length,j),b):j,g=Math.pow(10,e),h=(c(a+"e+"+e)/g).toFixed(e),d>b-e&&(f=new RegExp("\\.?0{1,"+(d-(b-e))+"}$"),h=h.replace(f,"")),h}},b.options=h,b.formats=e,b.locales=f,b.locale=function(a){return a&&(h.currentLocale=a.toLowerCase()),h.currentLocale},b.localeData=function(a){if(!a)return f[h.currentLocale];if(a=a.toLowerCase(),!f[a])throw new Error("Unknown locale : "+a);return f[a]},b.reset=function(){for(var a in g)h[a]=g[a]},b.zeroFormat=function(a){h.zeroFormat="string"==typeof a?a:null},b.nullFormat=function(a){h.nullFormat="string"==typeof a?a:null},b.defaultFormat=function(a){h.defaultFormat="string"==typeof a?a:"0.0"},b.register=function(a,b,c){if(b=b.toLowerCase(),this[a+"s"][b])throw new TypeError(b+" "+a+" already registered.");return this[a+"s"][b]=c,c},b.validate=function(a,c){var d,e,f,g,h,i,j,k;if("string"!=typeof a&&(a+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",a)),a=a.trim(),a.match(/^\d+$/))return!0;if(""===a)return!1;try{j=b.localeData(c)}catch(l){j=b.localeData(b.locale())}return f=j.currency.symbol,h=j.abbreviations,d=j.delimiters.decimal,e="."===j.delimiters.thousands?"\\.":j.delimiters.thousands,k=a.match(/^[^\d]+/),null!==k&&(a=a.substr(1),k[0]!==f)?!1:(k=a.match(/[^\d]+$/),null!==k&&(a=a.slice(0,-1),k[0]!==h.thousand&&k[0]!==h.million&&k[0]!==h.billion&&k[0]!==h.trillion)?!1:(i=new RegExp(e+"{2}"),a.match(/[^\d.,]/g)?!1:(g=a.split(d),g.length>2?!1:g.length<2?!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i):1===g[0].length?!!g[0].match(/^\d+$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/):!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/))))},b.fn=a.prototype={clone:function(){return b(this)},format:function(a,c){var d,f,g,i=this._value,j=a||h.defaultFormat;if(c=c||Math.round,0===i&&null!==h.zeroFormat)f=h.zeroFormat;else if(null===i&&null!==h.nullFormat)f=h.nullFormat;else{for(d in e)if(j.match(e[d].regexps.format)){g=e[d].format;break}g=g||b._.numberToFormat,f=g(i,j,c)}return f},value:function(){return this._value},input:function(){return this._input},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b,c,e){return a+Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([this._value,a],b,0)/d,this},subtract:function(a){function b(a,b,c,e){return a-Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([a],b,Math.round(this._value*d))/d,this},multiply:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)*Math.round(b*f)/Math.round(f*f)}return this._value=c.reduce([this._value,a],b,1),this},divide:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)/Math.round(b*f)}return this._value=c.reduce([this._value,a],b),this},difference:function(a){return Math.abs(b(this._value).subtract(a).value())}},b.register("locale","en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),function(){b.register("format","bps",{regexps:{format:/(BPS)/,unformat:/(BPS)/},format:function(a,c,d){var e,f=b._.includes(c," BPS")?" ":"";return a=1e4*a,c=c.replace(/\s?BPS/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"BPS"),e=e.join("")):e=e+f+"BPS",e},unformat:function(a){return+(1e-4*b._.stringToNumber(a)).toFixed(15)}})}(),function(){var a={base:1e3,suffixes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]},c={base:1024,suffixes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},d=a.suffixes.concat(c.suffixes.filter(function(b){return a.suffixes.indexOf(b)<0})),e=d.join("|");e="("+e.replace("B","B(?!PS)")+")",b.register("format","bytes",{regexps:{format:/([0\s]i?b)/,unformat:new RegExp(e)},format:function(d,e,f){var g,h,i,j,k=b._.includes(e,"ib")?c:a,l=b._.includes(e," b")||b._.includes(e," ib")?" ":"";for(e=e.replace(/\s?i?b/,""),h=0;h<=k.suffixes.length;h++)if(i=Math.pow(k.base,h),j=Math.pow(k.base,h+1),null===d||0===d||d>=i&&j>d){l+=k.suffixes[h],i>0&&(d/=i);break}return g=b._.numberToFormat(d,e,f),g+l},unformat:function(d){var e,f,g=b._.stringToNumber(d);if(g){for(e=a.suffixes.length-1;e>=0;e--){if(b._.includes(d,a.suffixes[e])){f=Math.pow(a.base,e);break}if(b._.includes(d,c.suffixes[e])){f=Math.pow(c.base,e);break}}g*=f||1}return g}})}(),function(){b.register("format","currency",{regexps:{format:/(\$)/},format:function(a,c,d){var e,f,g,h=b.locales[b.options.currentLocale],i={before:c.match(/^([\+|\-|\(|\s|\$]*)/)[0],after:c.match(/([\+|\-|\)|\s|\$]*)$/)[0]};for(c=c.replace(/\s?\$\s?/,""),e=b._.numberToFormat(a,c,d),a>=0?(i.before=i.before.replace(/[\-\(]/,""),i.after=i.after.replace(/[\-\)]/,"")):0>a&&!b._.includes(i.before,"-")&&!b._.includes(i.before,"(")&&(i.before="-"+i.before),g=0;g=0;g--)switch(f=i.after[g]){case"$":e=g===i.after.length-1?e+h.currency.symbol:b._.insert(e,h.currency.symbol,-(i.after.length-(1+g)));break;case" ":e=g===i.after.length-1?e+" ":b._.insert(e," ",-(i.after.length-(1+g)+h.currency.symbol.length-1))}return e}})}(),function(){b.register("format","exponential",{regexps:{format:/(e\+|e-)/,unformat:/(e\+|e-)/},format:function(a,c,d){var e,f="number"!=typeof a||b._.isNaN(a)?"0e+0":a.toExponential(),g=f.split("e");return c=c.replace(/e[\+|\-]{1}0/,""),e=b._.numberToFormat(Number(g[0]),c,d),e+"e"+g[1]},unformat:function(a){function c(a,c,d,e){var f=b._.correctionFactor(a,c),g=a*f*(c*f)/(f*f);return g}var d=b._.includes(a,"e+")?a.split("e+"):a.split("e-"),e=Number(d[0]),f=Number(d[1]);return f=b._.includes(a,"e-")?f*=-1:f,b._.reduce([e,Math.pow(10,f)],c,1)}})}(),function(){b.register("format","ordinal",{regexps:{format:/(o)/},format:function(a,c,d){var e,f=b.locales[b.options.currentLocale],g=b._.includes(c," o")?" ":"";return c=c.replace(/\s?o/,""),g+=f.ordinal(a),e=b._.numberToFormat(a,c,d),e+g}})}(),function(){b.register("format","percentage",{regexps:{format:/(%)/,unformat:/(%)/},format:function(a,c,d){var e,f=b._.includes(c," %")?" ":"";return b.options.scalePercentBy100&&(a=100*a),c=c.replace(/\s?\%/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"%"),e=e.join("")):e=e+f+"%",e},unformat:function(a){var c=b._.stringToNumber(a);return b.options.scalePercentBy100?.01*c:c}})}(),function(){b.register("format","time",{regexps:{format:/(:)/,unformat:/(:)/},format:function(a,b,c){var d=Math.floor(a/60/60),e=Math.floor((a-60*d*60)/60),f=Math.round(a-60*d*60-60*e);return d+":"+(10>e?"0"+e:e)+":"+(10>f?"0"+f:f)},unformat:function(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}})}(),b}); + +/***/ }), +/* 11 */ +/*!***************************!*\ + !*** ./utils/YesNoBox.js ***! + \***************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxCreate", function() { return yesNoBoxCreate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxCreate", function() { return yesNoTxtInpBoxCreate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxGetYesButton", function() { return yesNoBoxGetYesButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxGetNoButton", function() { return yesNoBoxGetNoButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetYesButton", function() { return yesNoTxtInpBoxGetYesButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetNoButton", function() { return yesNoTxtInpBoxGetNoButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetInput", function() { return yesNoTxtInpBoxGetInput; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxClose", function() { return yesNoBoxClose; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxClose", function() { return yesNoTxtInpBoxClose; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxOpen", function() { return yesNoBoxOpen; }); +/* harmony import */ var _HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HelperFunctions.js */ 1); + +/* Generic Yes-No Pop-up box + * Can be used to create pop-up boxes that require a yes/no response from player + */ +var yesNoBoxOpen = false; +function yesNoBoxClose() { + var container = document.getElementById("yes-no-box-container"); + if (container) { + container.style.display = "none"; + } else { + console.log("ERROR: Container not found for YesNoBox"); + } + yesNoBoxOpen = false; + return false; //So that 'return yesNoBoxClose()' is return false in event listeners +} + +function yesNoBoxGetYesButton() { + return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-yes"); +} + +function yesNoBoxGetNoButton() { + return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-no"); +} + +function yesNoBoxCreate(txt) { + if (yesNoBoxOpen) {return false;} //Already open + yesNoBoxOpen = true; + var textElement = document.getElementById("yes-no-box-text"); + if (textElement) { + textElement.innerHTML = txt; + } + + var c = document.getElementById("yes-no-box-container"); + if (c) { + c.style.display = "block"; + } else { + console.log("ERROR: Container not found for YesNoBox"); + } + return true; +} + +/* Generic Yes-No POp-up Box with Text input */ +function yesNoTxtInpBoxClose() { + var c = document.getElementById("yes-no-text-input-box-container"); + if (c) { + c.style.display = "none"; + } else { + console.log("ERROR: Container not found for YesNoTextInputBox"); + } + yesNoBoxOpen = false; + document.getElementById("yes-no-text-input-box-input").value = ""; + return false; +} + +function yesNoTxtInpBoxGetYesButton() { + return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-yes"); +} + +function yesNoTxtInpBoxGetNoButton() { + return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-no"); +} + +function yesNoTxtInpBoxGetInput() { + var val = document.getElementById("yes-no-text-input-box-input").value; + val = val.replace(/\s+/g, ''); + return val; +} + +function yesNoTxtInpBoxCreate(txt) { + yesNoBoxOpen = true; + var txtE = document.getElementById("yes-no-text-input-box-text"); + if (txtE) { + txtE.innerHTML = txt; + } + + var c = document.getElementById("yes-no-text-input-box-container"); + if (c) { + c.style.display = "block"; + } else { + console.log("ERROR: Container not found for YesNoTextInputBox"); + } + + document.getElementById("yes-no-text-input-box-input").focus(); +} + + + + +/***/ }), +/* 12 */ +/*!************************!*\ + !*** ./src/BitNode.js ***! + \************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initBitNodes", function() { return initBitNodes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNode", function() { return BitNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNodes", function() { return BitNodes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNodeMultipliers", function() { return BitNodeMultipliers; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initBitNodeMultipliers", function() { return initBitNodeMultipliers; }); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player.js */ 0); + + +function BitNode(n, name, desc="", info="") { + this.number = n; + this.name = name; + this.desc = desc; + this.info = info; +} + +let BitNodes = {}; +function initBitNodes() { + BitNodes = {}; + BitNodes["BitNode1"] = new BitNode(1, "Source Genesis", "The original BitNode", + "The first BitNode created by the Enders to imprison the minds of humans. It became " + + "the prototype and testing-grounds for all of the BitNodes that followed.

" + + "This is the first BitNode that you play through. It has no special " + + "modifications or mechanics.

" + + "Destroying this BitNode will give you Source-File 1, or if you already have " + + "this Source-File it will upgrade its level up to a maximum of 3. This Source-File " + + "lets the player start with 32GB of RAM on his/her home computer when entering a " + + "new BitNode, and also increases all of the player's multipliers by:

" + + "Level 1: 16%
" + + "Level 2: 24%
" + + "Level 3: 28%"); + BitNodes["BitNode2"] = new BitNode(2, "Rise of the Underworld", "From the shadows, they rose", //Gangs + "From the shadows, they rose.

Organized crime groups quickly filled the void of power " + + "left behind from the collapse of Western government in the 2050's. As society and civlization broke down, " + + "people quickly succumbed to the innate human impulse of evil and savagery. The organized crime " + + "factions quickly rose to the top of the modern world.

" + + "In this BitNode:

The maximum amount of money available on a server is significantly decreased
" + + "The amount of money gained from crimes and Infiltration is tripled
" + + "Certain Factions (Slum Snakes, Tetrads, The Syndicate, The Dark Army, Speakers for the Dead, " + + "NiteSec, The Black Hand) give the player the ability to form and manage their own gangs. These gangs " + + "will earn the player money and reputation with the corresponding Faction
" + + "Every Augmentation in the game will be available through the Factions listed above
" + + "For every Faction NOT listed above, reputation gains are halved
" + + "You will no longer gain passive reputation with Factions

" + + "Destroying this BitNode will give you Source-File 2, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File increases the player's crime success rate, " + + "crime money, and charisma multipliers by:

" + + "Level 1: 20%
" + + "Level 2: 30%
" + + "Level 3: 35%"); + BitNodes["BitNode3"] = new BitNode(3, "Corporatocracy", "The Price of Civilization", + "Our greatest illusion is that a healthy society can revolve around a " + + "single-minded pursuit of wealth.

" + + "Sometime in the early 21st century economic and political globalization turned " + + "the world into a corporatocracy, and it never looked back. Now, the privileged " + + "elite will happily bankrupt their own countrymen, decimate their own community, " + + "and evict their neighbors from houses in their desperate bid to increase their wealth.

" + + "In this BitNode you can create and manage your own corporation. Running a successful corporation " + + "has the potential of generating massive profits. All other forms of income are reduced by 75%. Furthermore:

" + + "The price and reputation cost of all Augmentations is tripled
" + + "The starting and maximum amount of money on servers is reduced by 75%
" + + "Server growth rate is reduced by 80%
" + + "You will start out with $150b so that you can start your corporation
" + + "You now only need 75 reputation with a faction in order to donate to it, rather than 150

" + + "Destroying this BitNode will give you Source-File 3, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File lets you create corporations on other BitNodes (although " + + "some BitNodes will disable this mechanic). This Source-File also increases your charisma and company salary multipliers by:
" + + "Level 1: 8%
" + + "Level 2: 12%
" + + "Level 3: 14%"); + BitNodes["BitNode4"] = new BitNode(4, "The Singularity", "The Man and the Machine", "The Singularity has arrived. The human race is gone, replaced " + + "by artificially superintelligent beings that are more machine than man.

" + + "In this BitNode, progressing is significantly harder. Experience gain rates " + + "for all stats are reduced. Most methods of earning money will now give significantly less.

" + + "In this BitNode you will gain access to a new set of Netscript Functions known as Singularity Functions. " + + "These functions allow you to control most aspects of the game through scripts, including working for factions/companies, " + + "purchasing/installing Augmentations, and creating programs.

" + + "Destroying this BitNode will give you Source-File 4, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File lets you access and use the Singularity " + + "Functions in other BitNodes. Each level of this Source-File will open up more Singularity Functions " + + "that you can use."); + BitNodes["BitNode5"] = new BitNode(5, "Artificial Intelligence", "Posthuman", "They said it couldn't be done. They said the human brain, " + + "along with its consciousness and intelligence, couldn't be replicated. They said the complexity " + + "of the brain results from unpredictable, nonlinear interactions that couldn't be modeled " + + "by 1's and 0's. They were wrong.

" + + "In this BitNode:

" + + "The base security level of servers is doubled
" + + "The starting money on servers is halved, but the maximum money remains the same
" + + "Most methods of earning money now give significantly less
" + + "Infiltration gives 50% more reputation and money
" + + "Corporations have 50% lower valuations and are therefore less profitable
" + + "Augmentations are more expensive
" + + "Hacking experience gain rates are reduced

" + + "Destroying this BitNode will give you Source-File 5, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File grants you a special new stat called Intelligence. " + + "Intelligence is unique because it is permanent and persistent (it never gets reset back to 1). However " + + "gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't know " + + "when you gain experience and how much). Higher Intelligence levels will boost your production for many actions " + + "in the game.

" + + "In addition, this Source-File will unlock the getBitNodeMultipliers() Netscript function, " + + "and will also raise all of your hacking-related multipliers by:

" + + "Level 1: 4%
" + + "Level 2: 6%
" + + "Level 3: 7%"); + BitNodes["BitNode6"] = new BitNode(6, "Bladeburners", "Like Tears in Rain", + "In the middle of the 21st century, OmniTek Incorporated began designing and manufacturing advanced synthetic " + + "androids, or Synthoids for short. They achieved a major technological breakthrough in the sixth generation " + + "of their Synthoid design, called MK-VI, by developing a hyperintelligent AI. Many argue that this was " + + "the first sentient AI ever created. This resulted in Synthoid models that were stronger, faster, and more intelligent " + + "than the humans that had created them.

" + + "In this BitNode you will be able to access the Bladeburner Division at the NSA, which provides a new mechanic " + + "for progression. Furthermore:

" + + "Hacking and Hacknet Nodes will be significantly less profitable
" + + "Your hacking level is reduced by 50%
" + + "Hacking experience gain from scripts is reduced by 75%
" + + "Corporations have 80% lower valuations and are therefore less profitable
" + + "Working for companies is 50% less profitable
" + + "Crimes and Infiltration are 50% less profitable

" + + "Destroying this BitNode will give you Source-File 6, or if you already have this Source-File it will upgrade " + + "its level up to a maximum of 3. This Source-File allows you to access the NSA's Bladeburner Division in other " + + "BitNodes. In addition, this Source-File will raise the experience gain rate of all your combat stats by:

" + + "Level 1: 8%
" + + "Level 2: 12%
" + + "Level 3: 14%"); + BitNodes["BitNode7"] = new BitNode(7, "Hacktocracy", "COMING SOON"); //Healthy Hacknet balancing mechanic + BitNodes["BitNode8"] = new BitNode(8, "Ghost of Wall Street", "Money never sleeps", + "You are trying to make a name for yourself as an up-and-coming hedge fund manager on Wall Street.

" + + "In this BitNode:

" + + "You start with $100 million
" + + "The only way to earn money is by trading on the stock market
" + + "You start with a WSE membership and access to the TIX API
" + + "You are able to short stocks and place different types of orders (limit/stop)
" + + "You can immediately donate to factions to gain reputation

" + + "Destroying this BitNode will give you Source-File 8, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File grants the following benefits:

" + + "Level 1: Permanent access to WSE and TIX API
" + + "Level 2: Ability to short stocks in other BitNodes
" + + "Level 3: Ability to use limit/stop orders in other BitNodes

" + + "This Source-File also increases your hacking growth multipliers by: " + + "
Level 1: 8%
Level 2: 12%
Level 3: 14%"); + BitNodes["BitNode9"] = new BitNode(9, "Do Androids Dream?", "COMING SOON"); + BitNodes["BitNode10"] = new BitNode(10, "MegaCorp", "COMING SOON"); //Not sure yet + BitNodes["BitNode11"] = new BitNode(11, "The Big Crash", "Okay. Sell it all.", + "The 2050s was defined by the massive amounts of violent civil unrest and anarchic rebellion that rose all around the world. It was this period " + + "of disorder that eventually lead to the governmental reformation of many global superpowers, most notably " + + "the USA and China. But just as the world was slowly beginning to recover from these dark times, financial catastrophe hit.

" + + "In many countries, the high cost of trying to deal with the civil disorder bankrupted the governments. In all of this chaos and confusion, hackers " + + "were able to steal billions of dollars from the world's largest electronic banks, prompting an international banking crisis as " + + "governments were unable to bail out insolvent banks. Now, the world is slowly crumbling in the middle of the biggest economic crisis of all time.

" + + "In this BitNode:

" + + "The starting and maximum amount of money available on servers is significantly decreased
" + + "The growth rate of servers is halved
" + + "Weakening a server is twice as effective
" + + "Company wages are decreased by 50%
" + + "Corporation valuations are 99% lower and are therefore significantly less profitable
" + + "Hacknet Node production is significantly decreased
" + + "Crime and Infiltration are more lucrative
" + + "Augmentations are twice as expensive

" + + "Destroying this BitNode will give you Source-File 11, or if you already have this Source-File it will " + + "upgrade its level up to a maximum of 3. This Source-File makes it so that company favor increases BOTH " + + "the player's salary and reputation gain rate at that company by 1% per favor (rather than just the reputation gain). " + + "This Source-File also increases the player's company salary and reputation gain multipliers by:

" + + "Level 1: 24%
" + + "Level 2: 36%
" + + "Level 3: 42%"); + + //Books: Frontera, Shiner + BitNodes["BitNode12"] = new BitNode(12, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes + BitNodes["BitNode13"] = new BitNode(13, "", "COMING SOON"); + BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON"); + BitNodes["BitNode15"] = new BitNode(15, "", "COMING SOON"); + BitNodes["BitNode16"] = new BitNode(16, "", "COMING SOON"); + BitNodes["BitNode17"] = new BitNode(17, "", "COMING SOON"); + BitNodes["BitNode18"] = new BitNode(18, "", "COMING SOON"); + BitNodes["BitNode19"] = new BitNode(19, "", "COMING SOON"); + BitNodes["BitNode20"] = new BitNode(20, "", "COMING SOON"); + BitNodes["BitNode21"] = new BitNode(21, "", "COMING SOON"); + BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON"); + BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON"); + BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON"); +} + +let BitNodeMultipliers = { + HackingLevelMultiplier: 1, + + ServerMaxMoney: 1, + ServerStartingMoney: 1, + ServerGrowthRate: 1, + ServerWeakenRate: 1, + ServerStartingSecurity: 1, + + ManualHackMoney: 1, + ScriptHackMoney: 1, + CompanyWorkMoney: 1, + CrimeMoney: 1, + HacknetNodeMoney: 1, + + CompanyWorkExpGain: 1, + ClassGymExpGain: 1, + FactionWorkExpGain: 1, + HackExpGain: 1, + CrimeExpGain: 1, + + FactionWorkRepGain: 1, + FactionPassiveRepGain: 1, + RepToDonateToFaction: 1, + + AugmentationRepCost: 1, + AugmentationMoneyCost: 1, + + InfiltrationMoney: 1, + InfiltrationRep: 1, + + CorporationValuation: 1, +} + +function initBitNodeMultipliers() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN == null) { + _Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN = 1; + } + for (var mult in BitNodeMultipliers) { + if (BitNodeMultipliers.hasOwnProperty(mult)) { + BitNodeMultipliers[mult] = 1; + } + } + + switch (_Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN) { + case 1: //Source Genesis (every multiplier is 1) + break; + case 2: //Rise of the Underworld + BitNodeMultipliers.ServerMaxMoney = 0.2; + BitNodeMultipliers.ServerStartingMoney = 0.4; + BitNodeMultipliers.CrimeMoney = 3; + BitNodeMultipliers.InfiltrationMoney = 3; + BitNodeMultipliers.FactionWorkRepGain = 0.5; + BitNodeMultipliers.FactionPassiveRepGain = 0; + break; + case 3: //Corporatocracy + BitNodeMultipliers.RepToDonateToFaction = 0.5; + BitNodeMultipliers.AugmentationRepCost = 3; + BitNodeMultipliers.AugmentationMoneyCost = 3; + BitNodeMultipliers.ServerMaxMoney = 0.25; + BitNodeMultipliers.ServerStartingMoney = 0.25; + BitNodeMultipliers.ServerGrowthRate = 0.20; + BitNodeMultipliers.ScriptHackMoney = 0.25; + BitNodeMultipliers.CompanyWorkMoney = 0.25; + BitNodeMultipliers.CrimeMoney = 0.25; + BitNodeMultipliers.HacknetNodeMoney = 0.25; + break; + case 4: //The Singularity + BitNodeMultipliers.ServerMaxMoney = 0.15; + BitNodeMultipliers.ServerStartingMoney = 0.75; + BitNodeMultipliers.ScriptHackMoney = 0.2; + BitNodeMultipliers.CompanyWorkMoney = 0.1; + BitNodeMultipliers.CrimeMoney = 0.2; + BitNodeMultipliers.HacknetNodeMoney = 0.05; + BitNodeMultipliers.CompanyWorkExpGain = 0.5; + BitNodeMultipliers.ClassGymExpGain = 0.5; + BitNodeMultipliers.FactionWorkExpGain = 0.5; + BitNodeMultipliers.HackExpGain = 0.4; + BitNodeMultipliers.CrimeExpGain = 0.5; + BitNodeMultipliers.FactionWorkRepGain = 0.75; + break; + case 5: //Artificial intelligence + BitNodeMultipliers.ServerMaxMoney = 2; + BitNodeMultipliers.ServerStartingSecurity = 2; + BitNodeMultipliers.ServerStartingMoney = 0.5; + BitNodeMultipliers.ScriptHackMoney = 0.15; + BitNodeMultipliers.HacknetNodeMoney = 0.2; + BitNodeMultipliers.CrimeMoney = 0.5; + BitNodeMultipliers.InfiltrationRep = 1.5; + BitNodeMultipliers.InfiltrationMoney = 1.5; + BitNodeMultipliers.AugmentationMoneyCost = 2; + BitNodeMultipliers.HackExpGain = 0.5; + BitNodeMultipliers.CorporationValuation = 0.5; + break; + case 6: //Bladeburner + BitNodeMultipliers.HackingLevelMultiplier = 0.5; + BitNodeMultipliers.ServerMaxMoney = 0.5; + BitNodeMultipliers.ServerStartingMoney = 0.5; + BitNodeMultipliers.ServerStartingSecurity = 1.5; + BitNodeMultipliers.ScriptHackMoney = 0.5; + BitNodeMultipliers.CompanyWorkMoney = 0.5; + BitNodeMultipliers.CrimeMoney = 0.5; + BitNodeMultipliers.InfiltrationMoney = 0.5; + BitNodeMultipliers.CorporationValuation = 0.2; + BitNodeMultipliers.HacknetNodeMoney = 0.2; + BitNodeMultipliers.FactionPassiveRepGain = 0; + BitNodeMultipliers.HackExpGain = 0.25; + break; + case 8: //Ghost of Wall Street + BitNodeMultipliers.ScriptHackMoney = 0; + BitNodeMultipliers.ManualHackMoney = 0; + BitNodeMultipliers.CompanyWorkMoney = 0; + BitNodeMultipliers.CrimeMoney = 0; + BitNodeMultipliers.HacknetNodeMoney = 0; + BitNodeMultipliers.InfiltrationMoney = 0; + BitNodeMultipliers.RepToDonateToFaction = 0; + BitNodeMultipliers.CorporationValuation = 0; + break; + case 11: //The Big Crash + BitNodeMultipliers.ServerMaxMoney = 0.1; + BitNodeMultipliers.ServerStartingMoney = 0.1; + BitNodeMultipliers.ServerGrowthRate = 0.5; + BitNodeMultipliers.ServerWeakenRate = 2; + BitNodeMultipliers.CrimeMoney = 3; + BitNodeMultipliers.CompanyWorkMoney = 0.5; + BitNodeMultipliers.HacknetNodeMoney = 0.1; + BitNodeMultipliers.AugmentationMoneyCost = 2; + BitNodeMultipliers.InfiltrationMoney = 2.5; + BitNodeMultipliers.InfiltrationRep = 2.5; + BitNodeMultipliers.CorporationValuation = 0.01; + break; + default: + console.log("WARNING: Player.bitNodeN invalid"); + break; + } +} + + + + +/***/ }), +/* 13 */ +/*!****************************!*\ + !*** ./utils/IPAddress.js ***! + \****************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomIp", function() { return createRandomIp; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ipExists", function() { return ipExists; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidIPAddress", function() { return isValidIPAddress; }); +/* harmony import */ var _src_Server_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Server.js */ 14); + +/* Functions to deal with manipulating IP addresses*/ + +//Generate a random IP address +//Will not return an IP address that already exists in the AllServers array +function createRandomIp() { + var ip = createRandomByte(99) +'.' + + createRandomByte(9) +'.' + + createRandomByte(9) +'.' + + createRandomByte(9); + + //If the Ip already exists, recurse to create a new one + if (ipExists(ip)) { + return createRandomIp(); + } + return ip; +} + +//Returns true if the IP already exists in one of the game's servers +function ipExists(ip) { + for (var property in _src_Server_js__WEBPACK_IMPORTED_MODULE_0__["AllServers"]) { + if (_src_Server_js__WEBPACK_IMPORTED_MODULE_0__["AllServers"].hasOwnProperty(property)) { + if (property == ip) { + return true; + } + } + } + return false; +} + +function createRandomByte(n=9) { + return Math.round(Math.random()*n); +} + +function isValidIPAddress(ipaddress) { + if (/^(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) + { + return true; + } + return false; +} + + + + +/***/ }), +/* 14 */ /*!***********************!*\ !*** ./src/Server.js ***! \***********************/ @@ -9791,15 +10119,15 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initForeignServers", function() { return initForeignServers; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeAllServers", function() { return prestigeAllServers; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeHomeComputer", function() { return prestigeHomeComputer; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram.js */ 14); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram.js */ 17); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); @@ -10719,2036 +11047,8 @@ Directory.prototype.getPath = function(name) { -/***/ }), -/* 11 */ -/*!************************!*\ - !*** ./src/Faction.js ***! - \************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNextNeurofluxLevel", function() { return getNextNeurofluxLevel; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Factions", function() { return Factions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initFactions", function() { return initFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inviteToFaction", function() { return inviteToFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinFaction", function() { return joinFaction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayFactionContent", function() { return displayFactionContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processPassiveFactionRepGain", function() { return processPassiveFactionRepGain; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFactions", function() { return loadFactions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Faction", function() { return Faction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseAugmentation", function() { return purchaseAugmentation; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factionExists", function() { return factionExists; }); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./FactionInfo.js */ 28); -/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Missions.js */ 34); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_FactionInvitationBox_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/FactionInvitationBox.js */ 116); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13__); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); - - - - - - - - - - - - - - - - - - -function Faction(name="") { - this.name = name; - this.augmentations = []; //Name of augmentation only - this.info = ""; //Introductory/informational text about the faction - - //Player-related properties for faction - this.isMember = false; //Whether player is member - this.isBanned = false; //Whether or not player is banned from joining this faction - this.playerReputation = 0; //"Reputation" within faction - this.alreadyInvited = false; - - //Multipliers for unlocking and purchasing augmentations - this.augmentationPriceMult = 1; - this.augmentationRepRequirementMult = 1; - - //Faction favor - this.favor = 0; - this.rolloverRep = 0; -}; - -Faction.prototype.setAugmentationMultipliers = function(price, rep) { - this.augmentationPriceMult = price; - this.augmentationRepRequirementMult = rep; -} - -Faction.prototype.setInfo = function(inf) { - this.info = inf; -} - -Faction.prototype.gainFavor = function() { - if (this.favor == null || this.favor == undefined) {this.favor = 0;} - if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} - var res = this.getFavorGain(); - if (res.length != 2) { - console.log("Error: invalid result from getFavorGain() function"); - return; - } - this.favor += res[0]; - this.rolloverRep = res[1]; -} - -//Returns an array with [How much favor would be gained, how much favor would be left over] -Faction.prototype.getFavorGain = function() { - if (this.favor == null || this.favor == undefined) {this.favor = 0;} - if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;} - var favorGain = 0, rep = this.playerReputation + this.rolloverRep; - var reqdRep = _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorBase * - Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult, this.favor); - while(rep > 0) { - if (rep >= reqdRep) { - ++favorGain; - rep -= reqdRep; - } else { - break; - } - reqdRep *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].FactionReputationToFavorMult; - } - return [favorGain, rep]; -} - -//Adds all Augmentations to this faction. -Faction.prototype.addAllAugmentations = function() { - this.augmentations.length = 0; - for (var name in _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) { - if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) { - this.augmentations.push(name); - } - } -} - -Faction.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Generic_toJSON"])("Faction", this); -} - -Faction.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Generic_fromJSON"])(Faction, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Reviver"].constructors.Faction = Faction; - -//Map of factions indexed by faction name -let Factions = {} - -function loadFactions(saveString) { - Factions = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_12__["Reviver"]); -} - -function AddToFactions(faction) { - var name = faction.name; - Factions[name] = faction; -} - -function factionExists(name) { - return Factions.hasOwnProperty(name); -} - -//TODO Augmentation price and rep requirement mult are 1 for everything right now, -// This might change in the future for balance -function initFactions() { - //Endgame - var Illuminati = new Faction("Illuminati"); - Illuminati.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].IlluminatiInfo); - resetFaction(Illuminati); - - var Daedalus = new Faction("Daedalus"); - Daedalus.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].DaedalusInfo); - resetFaction(Daedalus); - - var Covenant = new Faction("The Covenant"); - Covenant.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].CovenantInfo); - resetFaction(Covenant); - - //Megacorporations, each forms its own faction - var ECorp = new Faction("ECorp"); - ECorp.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].ECorpInfo); - resetFaction(ECorp); - - var MegaCorp = new Faction("MegaCorp"); - MegaCorp.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].MegaCorpInfo); - resetFaction(MegaCorp); - - var BachmanAndAssociates = new Faction("Bachman & Associates"); - BachmanAndAssociates.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].BachmanAndAssociatesInfo); - resetFaction(BachmanAndAssociates); - - var BladeIndustries = new Faction("Blade Industries"); - BladeIndustries.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].BladeIndustriesInfo); - resetFaction(BladeIndustries); - - var NWO = new Faction("NWO"); - NWO.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].NWOInfo); - resetFaction(NWO); - - var ClarkeIncorporated = new Faction("Clarke Incorporated"); - ClarkeIncorporated.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].ClarkeIncorporatedInfo); - resetFaction(ClarkeIncorporated); - - var OmniTekIncorporated = new Faction("OmniTek Incorporated"); - OmniTekIncorporated.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].OmniTekIncorporatedInfo); - resetFaction(OmniTekIncorporated); - - var FourSigma = new Faction("Four Sigma"); - FourSigma.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].FourSigmaInfo); - resetFaction(FourSigma); - - var KuaiGongInternational = new Faction("KuaiGong International"); - KuaiGongInternational.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].KuaiGongInternationalInfo); - resetFaction(KuaiGongInternational); - - //Other corporations - var FulcrumTechnologies = new Faction("Fulcrum Secret Technologies"); - FulcrumTechnologies.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].FulcrumSecretTechnologiesInfo); - resetFaction(FulcrumTechnologies); - - //Hacker groups - var BitRunners = new Faction("BitRunners"); - BitRunners.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].BitRunnersInfo); - resetFaction(BitRunners); - - var BlackHand = new Faction("The Black Hand"); - BlackHand.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].BlackHandInfo); - resetFaction(BlackHand); - - var NiteSec = new Faction("NiteSec"); - NiteSec.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].NiteSecInfo); - resetFaction(NiteSec); - - //City factions, essentially governments - var Chongqing = new Faction("Chongqing"); - Chongqing.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].ChongqingInfo); - resetFaction(Chongqing); - - var Sector12 = new Faction("Sector-12"); - Sector12.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].Sector12Info); - resetFaction(Sector12); - - var NewTokyo = new Faction("New Tokyo"); - NewTokyo.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].NewTokyoInfo); - resetFaction(NewTokyo); - - var Aevum = new Faction("Aevum"); - Aevum.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].AevumInfo); - resetFaction(Aevum); - - var Ishima = new Faction("Ishima"); - Ishima.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].Ishima); - resetFaction(Ishima); - - var Volhaven = new Faction("Volhaven"); - Volhaven.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].VolhavenInfo); - resetFaction(Volhaven); - - //Criminal Organizations/Gangs - var SpeakersForTheDead = new Faction("Speakers for the Dead"); - SpeakersForTheDead.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].SpeakersForTheDeadInfo); - resetFaction(SpeakersForTheDead); - - var DarkArmy = new Faction("The Dark Army"); - DarkArmy.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].DarkArmyInfo); - resetFaction(DarkArmy); - - var TheSyndicate = new Faction("The Syndicate"); - TheSyndicate.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].TheSyndicateInfo); - resetFaction(TheSyndicate); - - var Silhouette = new Faction("Silhouette"); - Silhouette.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].SilhouetteInfo); - resetFaction(Silhouette); - - var Tetrads = new Faction("Tetrads"); //Low-medium level asian crime gang - Tetrads.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].TetradsInfo); - resetFaction(Tetrads); - - var SlumSnakes = new Faction("Slum Snakes"); //Low level crime gang - SlumSnakes.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].SlumSnakesInfo); - resetFaction(SlumSnakes); - - //Earlygame factions - factions the player will prestige with early on that don't - //belong in other categories - var Netburners = new Faction("Netburners"); - Netburners.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].NetburnersInfo); - resetFaction(Netburners); - - var TianDiHui = new Faction("Tian Di Hui"); //Society of the Heaven and Earth - TianDiHui.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].TianDiHuiInfo); - resetFaction(TianDiHui); - - var CyberSec = new Faction("CyberSec"); - CyberSec.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].CyberSecInfo); - resetFaction(CyberSec); - - //Special Factions - var Bladeburners = new Faction("Bladeburners"); - Bladeburners.setInfo(_FactionInfo_js__WEBPACK_IMPORTED_MODULE_4__["FactionInfo"].BladeburnersInfo); - resetFaction(Bladeburners); -} - -//Resets a faction during (re-)initialization. Saves the favor in the new -//Faction object and deletes the old Faction Object from "Factions". Then -//reinserts the new Faction object -function resetFaction(newFactionObject) { - if (!(newFactionObject instanceof Faction)) { - throw new Error("Invalid argument 'newFactionObject' passed into resetFaction()"); - } - var factionName = newFactionObject.name; - if (factionExists(factionName)) { - newFactionObject.favor = Factions[factionName].favor; - delete Factions[factionName]; - } - AddToFactions(newFactionObject); -} - -function inviteToFaction(faction) { - if (_Settings_js__WEBPACK_IMPORTED_MODULE_8__["Settings"].SuppressFactionInvites) { - faction.alreadyInvited = true; - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].factionInvitations.push(faction.name); - if (_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Page.Factions) { - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionsContent(); - } - } else { - Object(_utils_FactionInvitationBox_js__WEBPACK_IMPORTED_MODULE_10__["factionInvitationBoxCreate"])(faction); - } -} - -function joinFaction(faction) { - faction.isMember = true; - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].factions.push(faction.name); - - //Determine what factions you are banned from now that you have joined this faction - if (faction.name == "Chongqing") { - Factions["Sector-12"].isBanned = true; - Factions["Aevum"].isBanned = true; - Factions["Volhaven"].isBanned = true; - } else if (faction.name == "Sector-12") { - Factions["Chongqing"].isBanned = true; - Factions["New Tokyo"].isBanned = true; - Factions["Ishima"].isBanned = true; - Factions["Volhaven"].isBanned = true; - } else if (faction.name == "New Tokyo") { - Factions["Sector-12"].isBanned = true; - Factions["Aevum"].isBanned = true; - Factions["Volhaven"].isBanned = true; - } else if (faction.name == "Aevum") { - Factions["Chongqing"].isBanned = true; - Factions["New Tokyo"].isBanned = true; - Factions["Ishima"].isBanned = true; - Factions["Volhaven"].isBanned = true; - } else if (faction.name == "Ishima") { - Factions["Sector-12"].isBanned = true; - Factions["Aevum"].isBanned = true; - Factions["Volhaven"].isBanned = true; - } else if (faction.name == "Volhaven") { - Factions["Chongqing"].isBanned = true; - Factions["Sector-12"].isBanned = true; - Factions["New Tokyo"].isBanned = true; - Factions["Aevum"].isBanned = true; - Factions["Ishima"].isBanned = true; - } -} - -//Displays the HTML content for a specific faction -function displayFactionContent(factionName) { - var faction = Factions[factionName]; - if (faction == null) { - throw new Error("Invalid factionName passed into displayFactionContent: " + factionName); - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent); - var elements = []; - - //Header and faction info - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", { - innerText:factionName - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - innerHTML:"" + faction.info + "" - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction reputation and favor - var favorGain = faction.getFavorGain(); - if (favorGain.length != 2) {favorGain = 0;} - favorGain = favorGain[0]; - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText: "Reputation: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(faction.playerReputation, 4), - tooltip:"You will earn " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(favorGain, 4) + - " faction favor upon resetting after installing an Augmentation" - })) - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Faction Favor: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(faction.favor, 4), - tooltip:"Faction favor increases the rate at which " + - "you earn reputation for this faction by 1% per favor. Faction favor " + - "is gained whenever you reset after installing an Augmentation. The amount of " + - "favor you gain depends on how much reputation you have with the faction" - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"---------------", - })); - - //Faction Work Description Text - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - id:"faction-work-description-text", - innerText:"Perform work/carry out assignments for your faction to help further its cause! By doing so " + - "you will earn reputation for your faction. You will also gain reputation passively over time, " + - "although at a very slow rate. Earning reputation will allow you to purchase Augmentations " + - "through this faction, which are powerful upgrades that enhance your abilities. Note that you cannot " + - "use your terminal or create scripts when you are performing a task!" - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - - //Hacking Mission Option - var hackMissionDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-hack-mission-div", class:"faction-work-div", - }); - var hackMissionDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackMissionDiv.appendChild(hackMissionDivWrapper); - hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Hacking Mission", - clickListener:()=>{ - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadMissionContent(); - var mission = new _Missions_js__WEBPACK_IMPORTED_MODULE_6__["HackingMission"](faction.playerReputation, faction); - Object(_Missions_js__WEBPACK_IMPORTED_MODULE_6__["setInMission"])(true, mission); //Sets inMission flag to true - mission.init(); - return false; - } - })); - hackMissionDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Attempt a hacking mission for your faction. " + - "A mission is a mini game that, if won, earns you " + - "significant reputation with this faction. (Recommended hacking level: 200+)" - })); - elements.push(hackMissionDiv); - - //Hacking Contracts Option - var hackDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-hack-div", class:"faction-work-div", - }); - var hackDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - hackDiv.appendChild(hackDivWrapper); - hackDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Hacking Contracts", - clickListener:()=>{ - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionHackWork(faction); - return false; - } - })); - hackDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Complete hacking contracts for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your hacking skill. " + - "You will gain hacking exp." - })); - elements.push(hackDiv); - - //Field Work Option - var fieldWorkDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-fieldwork-div", class:"faction-work-div" - }); - var fieldWorkDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - fieldWorkDiv.appendChild(fieldWorkDivWrapper); - fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Field Work", - clickListener:()=>{ - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionFieldWork(faction); - return false; - } - })); - fieldWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Carry out field missions for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on all of your stats. " + - "You will gain exp for all stats." - })); - elements.push(fieldWorkDiv); - - //Security Work Option - var securityWorkDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-securitywork-div", class:"faction-work-div" - }); - var securityWorkDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - securityWorkDiv.appendChild(securityWorkDivWrapper); - securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Security Work", - clickListener:()=>{ - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startFactionSecurityWork(faction); - return false; - } - })); - securityWorkDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Serve in a security detail for your faction. " + - "Your effectiveness, which determines how much " + - "reputation you gain for this faction, is based on your combat stats. " + - "You will gain exp for all combat stats." - })); - elements.push(securityWorkDiv); - - //Donate for reputation - var donateDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-donate-div", class:"faction-work-div" - }); - var donateDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - donateDiv.appendChild(donateDivWrapper); - var donateRepGain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"This donation will result in 0 reputation gain" - }); - var donateAmountInput = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", { - placeholder:"Donation amount", - inputListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { - donateRepGain.innerText = "Invalid donate amount entered!"; - } else { - var repGain = amt / 1e6 * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; - donateRepGain.innerText = "This donation will result in " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation gain"; - } - }, - }); - donateDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Donate Money", - clickListener:()=>{ - var amt = parseFloat(donateAmountInput.value); - if (isNaN(amt) || amt < 0) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Invalid amount entered!"); - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.lt(amt)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You cannot afford to donate this much money!"); - } else { - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].loseMoney(amt); - var repGain = amt / 1e6 * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; - faction.playerReputation += repGain; - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You just donated " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(amt).format("$0.000a") + " to " + - faction.name + " to gain " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(repGain, 3) + " reputation"); - displayFactionContent(factionName); - } - } - })); - donateDivWrapper.appendChild(donateAmountInput); - donateDivWrapper.appendChild(donateRepGain); - elements.push(donateDiv); - - //Purchase Augmentations - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("pre", { - innerHTML: "
As your reputation with this faction rises, you will " + - "unlock Augmentations, which you can purchase to enhance " + - "your abilities.

" - })); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Purchase Augmentations", - clickListener:()=>{ - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].hideAllContent(); - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.style.display = "block"; - - - displayFactionAugmentations(factionName); - return false; - } - })); - - //Gang (BitNode-2) - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].bitNodeN == 2 && (factionName == "Slum Snakes" || factionName == "Tetrads" || - factionName == "The Syndicate" || factionName == "The Dark Army" || factionName == "Speakers for the Dead" || - factionName == "NiteSec" || factionName == "The Black Hand")) { - //Set everything else to invisible - hackMissionDiv.style.display = "none"; - hackDiv.style.display = "none"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - donateDiv.style.display = "none"; - - //Create the 'Manage Gang' button - var gangDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", { - id:"faction-gang-div", class:"faction-work-div", display:"inline" - }); - var gangDivWrapper = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {class:"faction-work-div-wrapper"}); - gangDiv.appendChild(gangDivWrapper); - gangDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - class:"a-link-button", innerText:"Manage Gang", - clickListener:()=>{ - if (!_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].inGang()) { - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Create Gang"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", () => { - var hacking = false; - if (factionName === "NiteSec" || factionName === "The Black Hand") {hacking = true;} - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].startGang(factionName, hacking); - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent(); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); - }); - noBtn.addEventListener("click", () => { - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); - }); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxCreate"])("Would you like to create a new Gang with " + factionName + "?

" + - "Note that this will prevent you from creating a Gang with any other Faction until " + - "this BitNode is destroyed. There are NO differences between the Factions you can " + - "create a Gang with and each of these Factions have all Augmentations available"); - } else { - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadGangContent(); - } - } - })); - gangDivWrapper.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - innerText:"Create and manage a gang for this Faction. " + - "Gangs will earn you money and faction reputation." - })); - //Manage Gang button goes before Faction work stuff - elements.splice(7, 1, gangDiv); - - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].inGang() && _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gang.facName != factionName) { - //If the player has a gang but its not for this faction - gangDiv.style.display = "none"; - } - //Display all elements - for (var i = 0; i < elements.length; ++i) { - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]); - } - return; - } - - if (faction.isMember) { - if (faction.favor >= (150 * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].RepToDonateToFaction)) { - donateDiv.style.display = "inline"; - } else { - donateDiv.style.display = "none"; - } - - switch(faction.name) { - case "Illuminati": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "Daedalus": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "The Covenant": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "ECorp": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "MegaCorp": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Bachman & Associates": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Blade Industries": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "NWO": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Clarke Incorporated": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "OmniTek Incorporated": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Four Sigma": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "KuaiGong International": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Fulcrum Secret Technologies": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "inline"; - break; - case "BitRunners": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - break; - case "The Black Hand": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "NiteSec": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - break; - case "Chongqing": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Sector-12": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "New Tokyo": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Aevum": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Ishima": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Volhaven": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Speakers for the Dead": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "The Dark Army": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "The Syndicate": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Silhouette": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "none"; - break; - case "Tetrads": - hackMissionDiv.style.display = "none"; - hackDiv.style.display = "none"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Slum Snakes": - hackMissionDiv.style.display = "none"; - hackDiv.style.display = "none"; - fieldWorkDiv.style.display = "inline"; - securityWorkDiv.style.display = "inline"; - break; - case "Netburners": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - break; - case "Tian Di Hui": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "inline"; - break; - case "CyberSec": - hackMissionDiv.style.display = "inline"; - hackDiv.style.display = "inline"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - break; - case "Bladeburners": - hackMissionDiv.style.display = "none"; - hackDiv.style.display = "none"; - fieldWorkDiv.style.display = "none"; - securityWorkDiv.style.display = "none"; - break; - default: - console.log("Faction does not exist"); - break; - } - } else { - throw new Error("Not a member of this faction, cannot display faction information"); - } - - //Display all elements - for (var i = 0; i < elements.length; ++i) { - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionContent.appendChild(elements[i]); - } -} - -var confirmingPurchases = true; -var sortOption = null; -function displayFactionAugmentations(factionName) { - var faction = Factions[factionName]; - if (faction == null) { - throw new Error("Could not find faction " + factionName + " in displayFactionAugmentations"); - } - - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(_engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent); - var elements = []; - - //Back button - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Back", class:"a-link-button", - clickListener:()=>{ - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].loadFactionContent(); - displayFactionContent(factionName); - return false; - } - })); - - //Header text - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("h1", {innerText:"Faction Augmentations"})); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - id:"faction-augmentations-page-desc", - innerHTML:"Lists all Augmentations that are available to purchase from " + factionName + "

" + - "Augmentations are powerful upgrades that will enhance your abilities." - })); - - //Confirming not confirming button - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("label", { - for:"faction-augmentations-confirming-checkbox",innerText:"Confirm Purchases", - color:"white", margin:"4px", padding:"4px", - })); - var confirmingPurchasesCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("input", { - type:"checkbox", id:"faction-augmentations-confirming-checkbox", checked:confirmingPurchases, - margin:"4px", padding:"4px", - clickListener:()=>{ - confirmingPurchases = confirmingPurchasesCheckbox.checked; - } - }); - elements.push(confirmingPurchasesCheckbox); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - elements.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("br")); - - //Augmentations List - var augmentationsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("ul"); - - //Sort buttons - var sortByCostBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Cost", class:"a-link-button", - clickListener:()=>{ - sortOption = "cost"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseCost - aug2.baseCost; - }); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var sortByRepBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Reputation", class:"a-link-button", - clickListener:()=>{ - sortOption = "reputation"; - var augs = faction.augmentations.slice(); - augs.sort((augName1, augName2)=>{ - var aug1 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName1], aug2 = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName2]; - if (aug1 == null || aug2 == null) { - throw new Error("Invalid Augmentation Names"); - } - return aug1.baseRepRequirement - aug2.baseRepRequirement; - }); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, augs, faction); - } - }); - var defaultSortBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:"Sort by Default Order", class:"a-link-button", - clickListener:()=>{ - sortOption = "default"; - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["removeChildrenFromElement"])(augmentationsList); - createFactionAugmentationDisplayElements(augmentationsList, faction.augmentations, faction); - } - }); - elements.push(sortByCostBtn); - elements.push(sortByRepBtn); - elements.push(defaultSortBtn); - switch(sortOption) { - case "cost": - sortByCostBtn.click(); - break; - case "reputation": - sortByRepBtn.click(); - break; - default: - defaultSortBtn.click(); - break; - } - - elements.push(augmentationsList); - - for (var i = 0; i < elements.length; ++i) { - _engine_js__WEBPACK_IMPORTED_MODULE_3__["Engine"].Display.factionAugmentationsContent.appendChild(elements[i]); - } -} - -//Takes in an array of Augmentation Names, constructs DOM elements -//to list them on the faction page, and appends them to the given -//DOM element -// @augmentationsList DOM List to append Aug DOM elements to -// @augs Array of Aug names -// @faction Faction for which to display Augmentations -function createFactionAugmentationDisplayElements(augmentationsList, augs, faction) { - for (var i = 0; i < augs.length; ++i) { - (function () { - var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augs[i]]; - if (aug == null) { - throw new Error("Invalid Augmentation when trying to create Augmentation display Elements"); - } - var owned = false; - for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++j) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[j].name == aug.name) { - owned = true; - break; - } - } - for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations.length; ++j) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[j].name == aug.name) { - owned = true; - break; - } - } - - var item = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("li"); - var span = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("span", {display:"inline-block"}); - var aDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("div", {tooltip:aug.info}); - var aElem = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("a", { - innerText:aug.name, display:"inline", - clickListener:()=>{ - if (confirmingPurchases) { - purchaseAugmentationBoxCreate(aug, faction); - } else { - purchaseAugmentation(aug, faction); - } - return false; - } - }); - if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - aElem.innerText += " - Level " + (getNextNeurofluxLevel()); - } - var pElem = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["createElement"])("p", { - display:"inline", - }) - var req = aug.baseRepRequirement * faction.augmentationRepRequirementMult; - var hasPrereqs = hasAugmentationPrereqs(aug); - if (!hasPrereqs) { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "LOCKED (Requires " + aug.prereqs.join(",") + " as prerequisite(s))"; - pElem.style.color = "red"; - } else if (aug.name != _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor && (aug.owned || owned)) { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "ALREADY OWNED"; - } else if (faction.playerReputation >= req) { - aElem.setAttribute("class", "a-link-button"); - pElem.innerHTML = "UNLOCKED - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * faction.augmentationPriceMult).format("$0.000a"); - } else { - aElem.setAttribute("class", "a-link-button-inactive"); - pElem.innerHTML = "LOCKED (Requires " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(req, 1) + " faction reputation) - " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_13___default()(aug.baseCost * faction.augmentationPriceMult).format("$0.000a"); - pElem.style.color = "red"; - } - aDiv.appendChild(aElem); - span.appendChild(aDiv); - span.appendChild(pElem); - item.appendChild(span); - augmentationsList.appendChild(item); - }()); //Immediate invocation closure - } -} - -function purchaseAugmentationBoxCreate(aug, fac) { - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Purchase"; - noBtn.innerHTML = "Cancel"; - yesBtn.addEventListener("click", function() { - purchaseAugmentation(aug, fac); - }); - noBtn.addEventListener("click", function() { - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); - }); - - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxCreate"])("

" + aug.name + "


" + - aug.info + "

" + - "
Would you like to purchase the " + aug.name + " Augmentation for $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_14__["formatNumber"])(aug.baseCost * fac.augmentationPriceMult, 2) + "?"); -} - -//Returns a boolean indicating whether the player has the prerequisites for the -//specified Augmentation -function hasAugmentationPrereqs(aug) { - var hasPrereqs = true; - if (aug.prereqs && aug.prereqs.length > 0) { - for (var i = 0; i < aug.prereqs.length; ++i) { - var prereqAug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][aug.prereqs[i]]; - if (prereqAug == null) { - console.log("ERROR: Invalid prereq Augmentation: " + aug.prereqs[i]); - continue; - } - if (prereqAug.owned === false) { - hasPrereqs = false; - - //Check if the aug is purchased - for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++j) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[j].name === prereqAug.name) { - hasPrereqs = true; - break; - } - } - } - } - } - return hasPrereqs; -} - -function purchaseAugmentation(aug, fac, sing=false) { - var hasPrereqs = hasAugmentationPrereqs(aug); - if (!hasPrereqs) { - var txt = "You must first purchase or install " + aug.prereqs.join(",") + " before you can " + - "purchase this one."; - if (sing) {return txt;} else {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt);} - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.lt(aug.baseCost * fac.augmentationPriceMult)) { - let txt = "You don't have enough money to purchase " + aug.name; - if (sing) {return txt;} - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt); - } else if (fac.playerReputation < aug.baseRepRequirement) { - let txt = "You don't have enough faction reputation to purchase " + aug.name; - if (sing) {return txt;} - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])(txt); - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].money.gte(aug.baseCost * fac.augmentationPriceMult)) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].firstAugPurchased === false) { - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].firstAugPurchased = true; - document.getElementById("augmentations-tab").style.display = "list-item"; - document.getElementById("character-menu-header").click(); - document.getElementById("character-menu-header").click(); - } - - var queuedAugmentation = new _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["PlayerOwnedAugmentation"](aug.name); - if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - queuedAugmentation.level = getNextNeurofluxLevel(); - } - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.push(queuedAugmentation); - - _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].loseMoney((aug.baseCost * fac.augmentationPriceMult)); - - //If you just purchased Neuroflux Governor, recalculate the cost - if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - var nextLevel = getNextNeurofluxLevel(); - --nextLevel; - var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].NeuroFluxGovernorLevelMult, nextLevel); - aug.baseRepRequirement = 500 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationRepCost; - aug.baseCost = 750e3 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].AugmentationMoneyCost; - - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length-1; ++i) { - aug.baseCost *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier; - } - } - - for (var name in _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"]) { - if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"].hasOwnProperty(name)) { - _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][name].baseCost *= _Constants_js__WEBPACK_IMPORTED_MODULE_2__["CONSTANTS"].MultipleAugMultiplier; - } - } - - if (sing) { - return "You purchased " + aug.name; - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("You purchased " + aug.name + ". It's enhancements will not take " + - "effect until they are installed. To install your augmentations, go to the " + - "'Augmentations' tab on the left-hand navigation menu. Purchasing additional " + - "augmentations will now be more expensive."); - } - - displayFactionAugmentations(fac.name); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_9__["dialogBoxCreate"])("Hmm, something went wrong when trying to purchase an Augmentation. " + - "Please report this to the game developer with an explanation of how to " + - "reproduce this."); - } - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_15__["yesNoBoxClose"])(); -} - -function getNextNeurofluxLevel() { - var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor]; - if (aug == null) { - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations.length; ++i) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[i].name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - aug = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].augmentations[i]; - } - } - if (aug == null) { - console.log("WARNING: Could not find NeuroFlux Governor aug. This is OK if " + - "it happens during the loading/initialization of the game, but probably " + - "indicates something seriously wrong at other times"); - return 1; - } - } - var nextLevel = aug.level + 1; - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations.length; ++i) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].queuedAugmentations[i].name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) { - ++nextLevel; - } - } - return nextLevel; -} - -function processPassiveFactionRepGain(numCycles) { - var numTimesGain = (numCycles / 600) * _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].faction_rep_mult; - for (var name in Factions) { - if (Factions.hasOwnProperty(name)) { - var faction = Factions[name]; - - //TODO Get hard value of 1 rep per "rep gain cycle"" for now.. - //maybe later make this based on - //a player's 'status' like how powerful they are and how much money they have - if (faction.isMember) {faction.playerReputation += (numTimesGain * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionPassiveRepGain);} - } - } -} - - - - -/***/ }), -/* 12 */ -/*!***************************!*\ - !*** ./utils/YesNoBox.js ***! - \***************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxCreate", function() { return yesNoBoxCreate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxCreate", function() { return yesNoTxtInpBoxCreate; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxGetYesButton", function() { return yesNoBoxGetYesButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxGetNoButton", function() { return yesNoBoxGetNoButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetYesButton", function() { return yesNoTxtInpBoxGetYesButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetNoButton", function() { return yesNoTxtInpBoxGetNoButton; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxGetInput", function() { return yesNoTxtInpBoxGetInput; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxClose", function() { return yesNoBoxClose; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoTxtInpBoxClose", function() { return yesNoTxtInpBoxClose; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "yesNoBoxOpen", function() { return yesNoBoxOpen; }); -/* harmony import */ var _HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HelperFunctions.js */ 1); - -/* Generic Yes-No Pop-up box - * Can be used to create pop-up boxes that require a yes/no response from player - */ -var yesNoBoxOpen = false; -function yesNoBoxClose() { - var container = document.getElementById("yes-no-box-container"); - if (container) { - container.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoBox"); - } - yesNoBoxOpen = false; - return false; //So that 'return yesNoBoxClose()' is return false in event listeners -} - -function yesNoBoxGetYesButton() { - return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-yes"); -} - -function yesNoBoxGetNoButton() { - return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-box-no"); -} - -function yesNoBoxCreate(txt) { - if (yesNoBoxOpen) {return false;} //Already open - yesNoBoxOpen = true; - var textElement = document.getElementById("yes-no-box-text"); - if (textElement) { - textElement.innerHTML = txt; - } - - var c = document.getElementById("yes-no-box-container"); - if (c) { - c.style.display = "block"; - } else { - console.log("ERROR: Container not found for YesNoBox"); - } - return true; -} - -/* Generic Yes-No POp-up Box with Text input */ -function yesNoTxtInpBoxClose() { - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "none"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); - } - yesNoBoxOpen = false; - document.getElementById("yes-no-text-input-box-input").value = ""; - return false; -} - -function yesNoTxtInpBoxGetYesButton() { - return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-yes"); -} - -function yesNoTxtInpBoxGetNoButton() { - return Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_0__["clearEventListeners"])("yes-no-text-input-box-no"); -} - -function yesNoTxtInpBoxGetInput() { - var val = document.getElementById("yes-no-text-input-box-input").value; - val = val.replace(/\s+/g, ''); - return val; -} - -function yesNoTxtInpBoxCreate(txt) { - yesNoBoxOpen = true; - var txtE = document.getElementById("yes-no-text-input-box-text"); - if (txtE) { - txtE.innerHTML = txt; - } - - var c = document.getElementById("yes-no-text-input-box-container"); - if (c) { - c.style.display = "block"; - } else { - console.log("ERROR: Container not found for YesNoTextInputBox"); - } - - document.getElementById("yes-no-text-input-box-input").focus(); -} - - - - -/***/ }), -/* 13 */ -/*!*************************************************!*\ - !*** ./node_modules/numeral/min/numeral.min.js ***! - \*************************************************/ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @preserve - * numeral.js - * version : 2.0.6 - * author : Adam Draper - * license : MIT - * http://adamwdraper.github.com/Numeral-js/ - */ -!function(a,b){ true?!(__WEBPACK_AMD_DEFINE_FACTORY__ = (b), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : - __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):undefined}(this,function(){function a(a,b){this._input=a,this._value=b}var b,c,d="2.0.6",e={},f={},g={currentLocale:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0",scalePercentBy100:!0},h={currentLocale:g.currentLocale,zeroFormat:g.zeroFormat,nullFormat:g.nullFormat,defaultFormat:g.defaultFormat,scalePercentBy100:g.scalePercentBy100};return b=function(d){var f,g,i,j;if(b.isNumeral(d))f=d.value();else if(0===d||"undefined"==typeof d)f=0;else if(null===d||c.isNaN(d))f=null;else if("string"==typeof d)if(h.zeroFormat&&d===h.zeroFormat)f=0;else if(h.nullFormat&&d===h.nullFormat||!d.replace(/[^0-9]+/g,"").length)f=null;else{for(g in e)if(j="function"==typeof e[g].regexps.unformat?e[g].regexps.unformat():e[g].regexps.unformat,j&&d.match(j)){i=e[g].unformat;break}i=i||b._.stringToNumber,f=i(d)}else f=Number(d)||null;return new a(d,f)},b.version=d,b.isNumeral=function(b){return b instanceof a},b._=c={numberToFormat:function(a,c,d){var e,g,h,i,j,k,l,m=f[b.options.currentLocale],n=!1,o=!1,p=0,q="",r=1e12,s=1e9,t=1e6,u=1e3,v="",w=!1;if(a=a||0,g=Math.abs(a),b._.includes(c,"(")?(n=!0,c=c.replace(/[\(|\)]/g,"")):(b._.includes(c,"+")||b._.includes(c,"-"))&&(j=b._.includes(c,"+")?c.indexOf("+"):0>a?c.indexOf("-"):-1,c=c.replace(/[\+|\-]/g,"")),b._.includes(c,"a")&&(e=c.match(/a(k|m|b|t)?/),e=e?e[1]:!1,b._.includes(c," a")&&(q=" "),c=c.replace(new RegExp(q+"a[kmbt]?"),""),g>=r&&!e||"t"===e?(q+=m.abbreviations.trillion,a/=r):r>g&&g>=s&&!e||"b"===e?(q+=m.abbreviations.billion,a/=s):s>g&&g>=t&&!e||"m"===e?(q+=m.abbreviations.million,a/=t):(t>g&&g>=u&&!e||"k"===e)&&(q+=m.abbreviations.thousand,a/=u)),b._.includes(c,"[.]")&&(o=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],k=c.indexOf(","),p=(c.split(".")[0].split(",")[0].match(/0/g)||[]).length,i?(b._.includes(i,"[")?(i=i.replace("]",""),i=i.split("["),v=b._.toFixed(a,i[0].length+i[1].length,d,i[1].length)):v=b._.toFixed(a,i.length,d),h=v.split(".")[0],v=b._.includes(v,".")?m.delimiters.decimal+v.split(".")[1]:"",o&&0===Number(v.slice(1))&&(v="")):h=b._.toFixed(a,0,d),q&&!e&&Number(h)>=1e3&&q!==m.abbreviations.trillion)switch(h=String(Number(h)/1e3),q){case m.abbreviations.thousand:q=m.abbreviations.million;break;case m.abbreviations.million:q=m.abbreviations.billion;break;case m.abbreviations.billion:q=m.abbreviations.trillion}if(b._.includes(h,"-")&&(h=h.slice(1),w=!0),h.length0;x--)h="0"+h;return k>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+m.delimiters.thousands)),0===c.indexOf(".")&&(h=""),l=h+v+(q?q:""),n?l=(n&&w?"(":"")+l+(n&&w?")":""):j>=0?l=0===j?(w?"-":"+")+l:l+(w?"-":"+"):w&&(l="-"+l),l},stringToNumber:function(a){var b,c,d,e=f[h.currentLocale],g=a,i={thousand:3,million:6,billion:9,trillion:12};if(h.zeroFormat&&a===h.zeroFormat)c=0;else if(h.nullFormat&&a===h.nullFormat||!a.replace(/[^0-9]+/g,"").length)c=null;else{c=1,"."!==e.delimiters.decimal&&(a=a.replace(/\./g,"").replace(e.delimiters.decimal,"."));for(b in i)if(d=new RegExp("[^a-zA-Z]"+e.abbreviations[b]+"(?:\\)|(\\"+e.currency.symbol+")?(?:\\))?)?$"),g.match(d)){c*=Math.pow(10,i[b]);break}c*=(a.split("-").length+Math.min(a.split("(").length-1,a.split(")").length-1))%2?1:-1,a=a.replace(/[^0-9\.]+/g,""),c*=Number(a)}return c},isNaN:function(a){return"number"==typeof a&&isNaN(a)},includes:function(a,b){return-1!==a.indexOf(b)},insert:function(a,b,c){return a.slice(0,c)+b+a.slice(c)},reduce:function(a,b){if(null===this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof b)throw new TypeError(b+" is not a function");var c,d=Object(a),e=d.length>>>0,f=0;if(3===arguments.length)c=arguments[2];else{for(;e>f&&!(f in d);)f++;if(f>=e)throw new TypeError("Reduce of empty array with no initial value");c=d[f++]}for(;e>f;f++)f in d&&(c=b(c,d[f],f,d));return c},multiplier:function(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)},correctionFactor:function(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var d=c.multiplier(b);return a>d?a:d},1)},toFixed:function(a,b,c,d){var e,f,g,h,i=a.toString().split("."),j=b-(d||0);return e=2===i.length?Math.min(Math.max(i[1].length,j),b):j,g=Math.pow(10,e),h=(c(a+"e+"+e)/g).toFixed(e),d>b-e&&(f=new RegExp("\\.?0{1,"+(d-(b-e))+"}$"),h=h.replace(f,"")),h}},b.options=h,b.formats=e,b.locales=f,b.locale=function(a){return a&&(h.currentLocale=a.toLowerCase()),h.currentLocale},b.localeData=function(a){if(!a)return f[h.currentLocale];if(a=a.toLowerCase(),!f[a])throw new Error("Unknown locale : "+a);return f[a]},b.reset=function(){for(var a in g)h[a]=g[a]},b.zeroFormat=function(a){h.zeroFormat="string"==typeof a?a:null},b.nullFormat=function(a){h.nullFormat="string"==typeof a?a:null},b.defaultFormat=function(a){h.defaultFormat="string"==typeof a?a:"0.0"},b.register=function(a,b,c){if(b=b.toLowerCase(),this[a+"s"][b])throw new TypeError(b+" "+a+" already registered.");return this[a+"s"][b]=c,c},b.validate=function(a,c){var d,e,f,g,h,i,j,k;if("string"!=typeof a&&(a+="",console.warn&&console.warn("Numeral.js: Value is not string. It has been co-erced to: ",a)),a=a.trim(),a.match(/^\d+$/))return!0;if(""===a)return!1;try{j=b.localeData(c)}catch(l){j=b.localeData(b.locale())}return f=j.currency.symbol,h=j.abbreviations,d=j.delimiters.decimal,e="."===j.delimiters.thousands?"\\.":j.delimiters.thousands,k=a.match(/^[^\d]+/),null!==k&&(a=a.substr(1),k[0]!==f)?!1:(k=a.match(/[^\d]+$/),null!==k&&(a=a.slice(0,-1),k[0]!==h.thousand&&k[0]!==h.million&&k[0]!==h.billion&&k[0]!==h.trillion)?!1:(i=new RegExp(e+"{2}"),a.match(/[^\d.,]/g)?!1:(g=a.split(d),g.length>2?!1:g.length<2?!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i):1===g[0].length?!!g[0].match(/^\d+$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/):!!g[0].match(/^\d+.*\d$/)&&!g[0].match(i)&&!!g[1].match(/^\d+$/))))},b.fn=a.prototype={clone:function(){return b(this)},format:function(a,c){var d,f,g,i=this._value,j=a||h.defaultFormat;if(c=c||Math.round,0===i&&null!==h.zeroFormat)f=h.zeroFormat;else if(null===i&&null!==h.nullFormat)f=h.nullFormat;else{for(d in e)if(j.match(e[d].regexps.format)){g=e[d].format;break}g=g||b._.numberToFormat,f=g(i,j,c)}return f},value:function(){return this._value},input:function(){return this._input},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b,c,e){return a+Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([this._value,a],b,0)/d,this},subtract:function(a){function b(a,b,c,e){return a-Math.round(d*b)}var d=c.correctionFactor.call(null,this._value,a);return this._value=c.reduce([a],b,Math.round(this._value*d))/d,this},multiply:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)*Math.round(b*f)/Math.round(f*f)}return this._value=c.reduce([this._value,a],b,1),this},divide:function(a){function b(a,b,d,e){var f=c.correctionFactor(a,b);return Math.round(a*f)/Math.round(b*f)}return this._value=c.reduce([this._value,a],b),this},difference:function(a){return Math.abs(b(this._value).subtract(a).value())}},b.register("locale","en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),function(){b.register("format","bps",{regexps:{format:/(BPS)/,unformat:/(BPS)/},format:function(a,c,d){var e,f=b._.includes(c," BPS")?" ":"";return a=1e4*a,c=c.replace(/\s?BPS/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"BPS"),e=e.join("")):e=e+f+"BPS",e},unformat:function(a){return+(1e-4*b._.stringToNumber(a)).toFixed(15)}})}(),function(){var a={base:1e3,suffixes:["B","KB","MB","GB","TB","PB","EB","ZB","YB"]},c={base:1024,suffixes:["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"]},d=a.suffixes.concat(c.suffixes.filter(function(b){return a.suffixes.indexOf(b)<0})),e=d.join("|");e="("+e.replace("B","B(?!PS)")+")",b.register("format","bytes",{regexps:{format:/([0\s]i?b)/,unformat:new RegExp(e)},format:function(d,e,f){var g,h,i,j,k=b._.includes(e,"ib")?c:a,l=b._.includes(e," b")||b._.includes(e," ib")?" ":"";for(e=e.replace(/\s?i?b/,""),h=0;h<=k.suffixes.length;h++)if(i=Math.pow(k.base,h),j=Math.pow(k.base,h+1),null===d||0===d||d>=i&&j>d){l+=k.suffixes[h],i>0&&(d/=i);break}return g=b._.numberToFormat(d,e,f),g+l},unformat:function(d){var e,f,g=b._.stringToNumber(d);if(g){for(e=a.suffixes.length-1;e>=0;e--){if(b._.includes(d,a.suffixes[e])){f=Math.pow(a.base,e);break}if(b._.includes(d,c.suffixes[e])){f=Math.pow(c.base,e);break}}g*=f||1}return g}})}(),function(){b.register("format","currency",{regexps:{format:/(\$)/},format:function(a,c,d){var e,f,g,h=b.locales[b.options.currentLocale],i={before:c.match(/^([\+|\-|\(|\s|\$]*)/)[0],after:c.match(/([\+|\-|\)|\s|\$]*)$/)[0]};for(c=c.replace(/\s?\$\s?/,""),e=b._.numberToFormat(a,c,d),a>=0?(i.before=i.before.replace(/[\-\(]/,""),i.after=i.after.replace(/[\-\)]/,"")):0>a&&!b._.includes(i.before,"-")&&!b._.includes(i.before,"(")&&(i.before="-"+i.before),g=0;g=0;g--)switch(f=i.after[g]){case"$":e=g===i.after.length-1?e+h.currency.symbol:b._.insert(e,h.currency.symbol,-(i.after.length-(1+g)));break;case" ":e=g===i.after.length-1?e+" ":b._.insert(e," ",-(i.after.length-(1+g)+h.currency.symbol.length-1))}return e}})}(),function(){b.register("format","exponential",{regexps:{format:/(e\+|e-)/,unformat:/(e\+|e-)/},format:function(a,c,d){var e,f="number"!=typeof a||b._.isNaN(a)?"0e+0":a.toExponential(),g=f.split("e");return c=c.replace(/e[\+|\-]{1}0/,""),e=b._.numberToFormat(Number(g[0]),c,d),e+"e"+g[1]},unformat:function(a){function c(a,c,d,e){var f=b._.correctionFactor(a,c),g=a*f*(c*f)/(f*f);return g}var d=b._.includes(a,"e+")?a.split("e+"):a.split("e-"),e=Number(d[0]),f=Number(d[1]);return f=b._.includes(a,"e-")?f*=-1:f,b._.reduce([e,Math.pow(10,f)],c,1)}})}(),function(){b.register("format","ordinal",{regexps:{format:/(o)/},format:function(a,c,d){var e,f=b.locales[b.options.currentLocale],g=b._.includes(c," o")?" ":"";return c=c.replace(/\s?o/,""),g+=f.ordinal(a),e=b._.numberToFormat(a,c,d),e+g}})}(),function(){b.register("format","percentage",{regexps:{format:/(%)/,unformat:/(%)/},format:function(a,c,d){var e,f=b._.includes(c," %")?" ":"";return b.options.scalePercentBy100&&(a=100*a),c=c.replace(/\s?\%/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"%"),e=e.join("")):e=e+f+"%",e},unformat:function(a){var c=b._.stringToNumber(a);return b.options.scalePercentBy100?.01*c:c}})}(),function(){b.register("format","time",{regexps:{format:/(:)/,unformat:/(:)/},format:function(a,b,c){var d=Math.floor(a/60/60),e=Math.floor((a-60*d*60)/60),f=Math.round(a-60*d*60-60*e);return d+":"+(10>e?"0"+e:e)+":"+(10>f?"0"+f:f)},unformat:function(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}})}(),b}); - -/***/ }), -/* 14 */ -/*!******************************!*\ - !*** ./src/CreateProgram.js ***! - \******************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Programs", function() { return Programs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayCreateProgramContent", function() { return displayCreateProgramContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNumAvailableCreateProgram", function() { return getNumAvailableCreateProgram; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initCreateProgramButtons", function() { return initCreateProgramButtons; }); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); - - - - -/* Create programs */ -let Programs = { - NukeProgram: "NUKE.exe", - BruteSSHProgram: "BruteSSH.exe", - FTPCrackProgram: "FTPCrack.exe", - RelaySMTPProgram: "relaySMTP.exe", - HTTPWormProgram: "HTTPWorm.exe", - SQLInjectProgram: "SQLInject.exe", - DeepscanV1: "DeepscanV1.exe", - DeepscanV2: "DeepscanV2.exe", - ServerProfiler: "ServerProfiler.exe", - AutoLink: "AutoLink.exe", - Flight: "fl1ght.exe", - BitFlume: "b1t_flum3.exe" -}; - -var nukeALink, bruteSshALink, ftpCrackALink, relaySmtpALink, httpWormALink, sqlInjectALink, - deepscanv1ALink, deepscanv2ALink, servProfilerALink, autolinkALink, bitFlumeALink; -function displayCreateProgramContent() { - nukeALink.style.display = "none"; - bruteSshALink.style.display = "none"; - ftpCrackALink.style.display = "none"; - relaySmtpALink.style.display = "none"; - httpWormALink.style.display = "none"; - sqlInjectALink.style.display = "none"; - deepscanv1ALink.style.display = "none"; - deepscanv2ALink.style.display = "none"; - servProfilerALink.style.display = "none"; - autolinkALink.style.display = "none"; - bitFlumeALink.style.display = "none"; - - //NUKE.exe (in case you delete it lol) - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) { - nukeALink.style.display = "inline-block"; - } - //BruteSSH - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 50) { - bruteSshALink.style.display = "inline-block"; - } - //FTPCrack - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 100) { - ftpCrackALink.style.display = "inline-block"; - } - //relaySMTP - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 250) { - relaySmtpALink.style.display = "inline-block"; - } - //HTTPWorm - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 500) { - httpWormALink.style.display = "inline-block"; - } - //SQLInject - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 750) { - sqlInjectALink.style.display = "inline-block"; - } - //Deepscan V1 and V2 - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV1) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { - deepscanv1ALink.style.display = "inline-block"; - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV2) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 400) { - deepscanv2ALink.style.display = "inline-block"; - } - //Server profiler - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.ServerProfiler) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { - servProfilerALink.style.display = "inline-block"; - } - //Auto Link - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.AutoLink) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 25) { - autolinkALink.style.display = "inline-block"; - } - //Bit Flume - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.BitFlume) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].sourceFiles.length > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 5) { - bitFlumeALink.style.display = "inline-block"; - } -} - -//Returns the number of programs that are currently available to be created -function getNumAvailableCreateProgram() { - var count = 0; - //PortHack.exe (in case you delete it lol) - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) { - ++count; - } - //BruteSSH - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 50) { - ++count; - } - //FTPCrack - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 100) { - ++count; - } - //relaySMTP - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 250) { - ++count; - } - //HTTPWorm - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 500) { - ++count; - } - //SQLInject - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 && - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 750) { - ++count; - } - //Deepscan V1 and V2 - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV1) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { - ++count; - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV2) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 400) { - ++count; - } - //Server profiler - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.ServerProfiler) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { - ++count; - } - //Auto link - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.AutoLink) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 25) { - ++count; - } - //Bit Flume - if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.BitFlume) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].sourceFiles.length > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 5) { - ++count; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable === false && count > 0) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable = true; - document.getElementById("create-program-tab").style.display = "list-item"; - document.getElementById("hacking-menu-header").click(); - document.getElementById("hacking-menu-header").click(); - } - return count; -} - -function initCreateProgramButtons() { - var createProgramList = document.getElementById("create-program-list"); - nukeALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-nuke", innerText:Programs.NukeProgram, - tooltip:"This virus is used to gain root access to a machine if enough ports are opened.", - }); - createProgramList.appendChild(nukeALink); - - bruteSshALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-brutessh", innerText:Programs.BruteSSHProgram, - tooltip:"This program executes a brute force attack that opens SSH ports" - }); - createProgramList.appendChild(bruteSshALink); - - ftpCrackALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-ftpcrack", innerText:Programs.FTPCrackProgram, - tooltip:"This program cracks open FTP ports" - }); - createProgramList.appendChild(ftpCrackALink); - - relaySmtpALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-relaysmtp", innerText:Programs.RelaySMTPProgram, - tooltip:"This program opens SMTP ports by redirecting data" - }) ; - createProgramList.appendChild(relaySmtpALink); - - httpWormALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-httpworm", innerText:Programs.HTTPWormProgram, - tooltip:"This virus opens up HTTP ports" - }); - createProgramList.appendChild(httpWormALink); - - sqlInjectALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-sqlinject", innerText:Programs.SQLInjectProgram, - tooltip:"This virus opens SQL ports" - }); - createProgramList.appendChild(sqlInjectALink); - - deepscanv1ALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-deepscanv1", innerText:Programs.DeepscanV1, - tooltip:"This program allows you to use the scan-analyze command with a depth up to 5" - }); - createProgramList.appendChild(deepscanv1ALink); - - deepscanv2ALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-deepscanv2", innerText:Programs.DeepscanV2, - tooltip:"This program allows you to use the scan-analyze command with a depth up to 10" - }); - createProgramList.appendChild(deepscanv2ALink); - - servProfilerALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-serverprofiler", innerText:Programs.ServerProfiler, - tooltip:"This program is used to display hacking and Netscript-related information about servers" - }); - createProgramList.appendChild(servProfilerALink); - - bitFlumeALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-bitflume", innerText:Programs.BitFlume, - tooltip:"This program creates a portal to the BitNode Nexus (allows you to restart and switch BitNodes)" - }); - createProgramList.appendChild(bitFlumeALink); - - autolinkALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { - class:"a-link-button", id:"create-program-autolink", innerText:"AutoLink.exe", - tooltip:"This program allows you to directly connect to other servers through the 'scan-analyze' command" - }); - createProgramList.appendChild(autolinkALink); - - nukeALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.NukeProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes, 1); - return false; - }); - bruteSshALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.BruteSSHProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes * 2, 50); - return false; - }); - ftpCrackALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.FTPCrackProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour, 100); - return false; - }); - relaySmtpALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.RelaySMTPProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours, 250); - return false; - }); - httpWormALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.HTTPWormProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer4Hours, 500); - return false; - }); - sqlInjectALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.SQLInjectProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer8Hours, 750); - return false; - }); - deepscanv1ALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.DeepscanV1, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour, 75); - return false; - }); - deepscanv2ALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.DeepscanV2, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours, 400); - return false; - }); - servProfilerALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.ServerProfiler, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour, 75); - return false; - }); - autolinkALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.AutoLink, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour, 25); - return false; - }); - bitFlumeALink.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.BitFlume, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes / 5, 5); - return false; - }); -} - - - - /***/ }), /* 15 */ -/*!************************!*\ - !*** ./src/BitNode.js ***! - \************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initBitNodes", function() { return initBitNodes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNode", function() { return BitNode; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNodes", function() { return BitNodes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BitNodeMultipliers", function() { return BitNodeMultipliers; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initBitNodeMultipliers", function() { return initBitNodeMultipliers; }); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player.js */ 0); - - -function BitNode(n, name, desc="", info="") { - this.number = n; - this.name = name; - this.desc = desc; - this.info = info; -} - -let BitNodes = {}; -function initBitNodes() { - BitNodes = {}; - BitNodes["BitNode1"] = new BitNode(1, "Source Genesis", "The original BitNode", - "The first BitNode created by the Enders to imprison the minds of humans. It became " + - "the prototype and testing-grounds for all of the BitNodes that followed.

" + - "This is the first BitNode that you play through. It has no special " + - "modifications or mechanics.

" + - "Destroying this BitNode will give you Source-File 1, or if you already have " + - "this Source-File it will upgrade its level up to a maximum of 3. This Source-File " + - "lets the player start with 32GB of RAM on his/her home computer when entering a " + - "new BitNode, and also increases all of the player's multipliers by:

" + - "Level 1: 16%
" + - "Level 2: 24%
" + - "Level 3: 28%"); - BitNodes["BitNode2"] = new BitNode(2, "Rise of the Underworld", "From the shadows, they rose", //Gangs - "From the shadows, they rose.

Organized crime groups quickly filled the void of power " + - "left behind from the collapse of Western government in the 2050's. As society and civlization broke down, " + - "people quickly succumbed to the innate human impulse of evil and savagery. The organized crime " + - "factions quickly rose to the top of the modern world.

" + - "In this BitNode:

The maximum amount of money available on a server is significantly decreased
" + - "The amount of money gained from crimes and Infiltration is tripled
" + - "Certain Factions (Slum Snakes, Tetrads, The Syndicate, The Dark Army, Speakers for the Dead, " + - "NiteSec, The Black Hand) give the player the ability to form and manage their own gangs. These gangs " + - "will earn the player money and reputation with the corresponding Faction
" + - "Every Augmentation in the game will be available through the Factions listed above
" + - "For every Faction NOT listed above, reputation gains are halved
" + - "You will no longer gain passive reputation with Factions

" + - "Destroying this BitNode will give you Source-File 2, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File increases the player's crime success rate, " + - "crime money, and charisma multipliers by:

" + - "Level 1: 20%
" + - "Level 2: 30%
" + - "Level 3: 35%"); - BitNodes["BitNode3"] = new BitNode(3, "Corporatocracy", "The Price of Civilization", - "Our greatest illusion is that a healthy society can revolve around a " + - "single-minded pursuit of wealth.

" + - "Sometime in the early 21st century economic and political globalization turned " + - "the world into a corporatocracy, and it never looked back. Now, the privileged " + - "elite will happily bankrupt their own countrymen, decimate their own community, " + - "and evict their neighbors from houses in their desperate bid to increase their wealth.

" + - "In this BitNode you can create and manage your own corporation. Running a successful corporation " + - "has the potential of generating massive profits. All other forms of income are reduced by 75%. Furthermore:

" + - "The price and reputation cost of all Augmentations is tripled
" + - "The starting and maximum amount of money on servers is reduced by 75%
" + - "Server growth rate is reduced by 80%
" + - "You will start out with $150b so that you can start your corporation
" + - "You now only need 75 reputation with a faction in order to donate to it, rather than 150

" + - "Destroying this BitNode will give you Source-File 3, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File lets you create corporations on other BitNodes (although " + - "some BitNodes will disable this mechanic). This Source-File also increases your charisma and company salary multipliers by:
" + - "Level 1: 8%
" + - "Level 2: 12%
" + - "Level 3: 14%"); - BitNodes["BitNode4"] = new BitNode(4, "The Singularity", "The Man and the Machine", "The Singularity has arrived. The human race is gone, replaced " + - "by artificially superintelligent beings that are more machine than man.

" + - "In this BitNode, progressing is significantly harder. Experience gain rates " + - "for all stats are reduced. Most methods of earning money will now give significantly less.

" + - "In this BitNode you will gain access to a new set of Netscript Functions known as Singularity Functions. " + - "These functions allow you to control most aspects of the game through scripts, including working for factions/companies, " + - "purchasing/installing Augmentations, and creating programs.

" + - "Destroying this BitNode will give you Source-File 4, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File lets you access and use the Singularity " + - "Functions in other BitNodes. Each level of this Source-File will open up more Singularity Functions " + - "that you can use."); - BitNodes["BitNode5"] = new BitNode(5, "Artificial Intelligence", "Posthuman", "They said it couldn't be done. They said the human brain, " + - "along with its consciousness and intelligence, couldn't be replicated. They said the complexity " + - "of the brain results from unpredictable, nonlinear interactions that couldn't be modeled " + - "by 1's and 0's. They were wrong.

" + - "In this BitNode:

" + - "The base security level of servers is doubled
" + - "The starting money on servers is halved, but the maximum money remains the same
" + - "Most methods of earning money now give significantly less
" + - "Infiltration gives 50% more reputation and money
" + - "Corporations have 50% lower valuations and are therefore less profitable
" + - "Augmentations are more expensive
" + - "Hacking experience gain rates are reduced

" + - "Destroying this BitNode will give you Source-File 5, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File grants you a special new stat called Intelligence. " + - "Intelligence is unique because it is permanent and persistent (it never gets reset back to 1). However " + - "gaining Intelligence experience is much slower than other stats, and it is also hidden (you won't know " + - "when you gain experience and how much). Higher Intelligence levels will boost your production for many actions " + - "in the game.

" + - "In addition, this Source-File will unlock the getBitNodeMultipliers() Netscript function, " + - "and will also raise all of your hacking-related multipliers by:

" + - "Level 1: 4%
" + - "Level 2: 6%
" + - "Level 3: 7%"); - BitNodes["BitNode6"] = new BitNode(6, "Bladeburners", "Like Tears in Rain", - "In the middle of the 21st century, OmniTek Incorporated began designing and manufacturing advanced synthetic " + - "androids, or Synthoids for short. They achieved a major technological breakthrough in the sixth generation " + - "of their Synthoid design, called MK-VI, by developing a hyperintelligent AI. Many argue that this was " + - "the first sentient AI ever created. This resulted in Synthoid models that were stronger, faster, and more intelligent " + - "than the humans that had created them.

" + - "In this BitNode you will be able to access the Bladeburner Division at the NSA, which provides a new mechanic " + - "for progression. Furthermore:

" + - "Hacking and Hacknet Nodes will be significantly less profitable
" + - "Your hacking level is reduced by 50%
" + - "Hacking experience gain from scripts is reduced by 75%
" + - "Corporations have 80% lower valuations and are therefore less profitable
" + - "Working for companies is 50% less profitable
" + - "Crimes and Infiltration are 50% less profitable

" + - "Destroying this BitNode will give you Source-File 6, or if you already have this Source-File it will upgrade " + - "its level up to a maximum of 3. This Source-File allows you to access the NSA's Bladeburner Division in other " + - "BitNodes. In addition, this Source-File will raise the experience gain rate of all your combat stats by:

" + - "Level 1: 8%
" + - "Level 2: 12%
" + - "Level 3: 14%"); - BitNodes["BitNode7"] = new BitNode(7, "Hacktocracy", "COMING SOON"); //Healthy Hacknet balancing mechanic - BitNodes["BitNode8"] = new BitNode(8, "Ghost of Wall Street", "Money never sleeps", - "You are trying to make a name for yourself as an up-and-coming hedge fund manager on Wall Street.

" + - "In this BitNode:

" + - "You start with $100 million
" + - "The only way to earn money is by trading on the stock market
" + - "You start with a WSE membership and access to the TIX API
" + - "You are able to short stocks and place different types of orders (limit/stop)
" + - "You can immediately donate to factions to gain reputation

" + - "Destroying this BitNode will give you Source-File 8, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File grants the following benefits:

" + - "Level 1: Permanent access to WSE and TIX API
" + - "Level 2: Ability to short stocks in other BitNodes
" + - "Level 3: Ability to use limit/stop orders in other BitNodes

" + - "This Source-File also increases your hacking growth multipliers by: " + - "
Level 1: 8%
Level 2: 12%
Level 3: 14%"); - BitNodes["BitNode9"] = new BitNode(9, "Do Androids Dream?", "COMING SOON"); - BitNodes["BitNode10"] = new BitNode(10, "MegaCorp", "COMING SOON"); //Not sure yet - BitNodes["BitNode11"] = new BitNode(11, "The Big Crash", "Okay. Sell it all.", - "The 2050s was defined by the massive amounts of violent civil unrest and anarchic rebellion that rose all around the world. It was this period " + - "of disorder that eventually lead to the governmental reformation of many global superpowers, most notably " + - "the USA and China. But just as the world was slowly beginning to recover from these dark times, financial catastrophe hit.

" + - "In many countries, the high cost of trying to deal with the civil disorder bankrupted the governments. In all of this chaos and confusion, hackers " + - "were able to steal billions of dollars from the world's largest electronic banks, prompting an international banking crisis as " + - "governments were unable to bail out insolvent banks. Now, the world is slowly crumbling in the middle of the biggest economic crisis of all time.

" + - "In this BitNode:

" + - "The starting and maximum amount of money available on servers is significantly decreased
" + - "The growth rate of servers is halved
" + - "Weakening a server is twice as effective
" + - "Company wages are decreased by 50%
" + - "Corporation valuations are 99% lower and are therefore significantly less profitable
" + - "Hacknet Node production is significantly decreased
" + - "Crime and Infiltration are more lucrative
" + - "Augmentations are twice as expensive

" + - "Destroying this BitNode will give you Source-File 11, or if you already have this Source-File it will " + - "upgrade its level up to a maximum of 3. This Source-File makes it so that company favor increases BOTH " + - "the player's salary and reputation gain rate at that company by 1% per favor (rather than just the reputation gain). " + - "This Source-File also increases the player's company salary and reputation gain multipliers by:

" + - "Level 1: 24%
" + - "Level 2: 36%
" + - "Level 3: 42%"); - - //Books: Frontera, Shiner - BitNodes["BitNode12"] = new BitNode(12, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes - BitNodes["BitNode13"] = new BitNode(13, "", "COMING SOON"); - BitNodes["BitNode14"] = new BitNode(14, "", "COMING SOON"); - BitNodes["BitNode15"] = new BitNode(15, "", "COMING SOON"); - BitNodes["BitNode16"] = new BitNode(16, "", "COMING SOON"); - BitNodes["BitNode17"] = new BitNode(17, "", "COMING SOON"); - BitNodes["BitNode18"] = new BitNode(18, "", "COMING SOON"); - BitNodes["BitNode19"] = new BitNode(19, "", "COMING SOON"); - BitNodes["BitNode20"] = new BitNode(20, "", "COMING SOON"); - BitNodes["BitNode21"] = new BitNode(21, "", "COMING SOON"); - BitNodes["BitNode22"] = new BitNode(22, "", "COMING SOON"); - BitNodes["BitNode23"] = new BitNode(23, "", "COMING SOON"); - BitNodes["BitNode24"] = new BitNode(24, "", "COMING SOON"); -} - -let BitNodeMultipliers = { - HackingLevelMultiplier: 1, - - ServerMaxMoney: 1, - ServerStartingMoney: 1, - ServerGrowthRate: 1, - ServerWeakenRate: 1, - ServerStartingSecurity: 1, - - ManualHackMoney: 1, - ScriptHackMoney: 1, - CompanyWorkMoney: 1, - CrimeMoney: 1, - HacknetNodeMoney: 1, - - CompanyWorkExpGain: 1, - ClassGymExpGain: 1, - FactionWorkExpGain: 1, - HackExpGain: 1, - CrimeExpGain: 1, - - FactionWorkRepGain: 1, - FactionPassiveRepGain: 1, - RepToDonateToFaction: 1, - - AugmentationRepCost: 1, - AugmentationMoneyCost: 1, - - InfiltrationMoney: 1, - InfiltrationRep: 1, - - CorporationValuation: 1, -} - -function initBitNodeMultipliers() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN == null) { - _Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN = 1; - } - for (var mult in BitNodeMultipliers) { - if (BitNodeMultipliers.hasOwnProperty(mult)) { - BitNodeMultipliers[mult] = 1; - } - } - - switch (_Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].bitNodeN) { - case 1: //Source Genesis (every multiplier is 1) - break; - case 2: //Rise of the Underworld - BitNodeMultipliers.ServerMaxMoney = 0.2; - BitNodeMultipliers.ServerStartingMoney = 0.4; - BitNodeMultipliers.CrimeMoney = 3; - BitNodeMultipliers.InfiltrationMoney = 3; - BitNodeMultipliers.FactionWorkRepGain = 0.5; - BitNodeMultipliers.FactionPassiveRepGain = 0; - break; - case 3: //Corporatocracy - BitNodeMultipliers.RepToDonateToFaction = 0.5; - BitNodeMultipliers.AugmentationRepCost = 3; - BitNodeMultipliers.AugmentationMoneyCost = 3; - BitNodeMultipliers.ServerMaxMoney = 0.25; - BitNodeMultipliers.ServerStartingMoney = 0.25; - BitNodeMultipliers.ServerGrowthRate = 0.20; - BitNodeMultipliers.ScriptHackMoney = 0.25; - BitNodeMultipliers.CompanyWorkMoney = 0.25; - BitNodeMultipliers.CrimeMoney = 0.25; - BitNodeMultipliers.HacknetNodeMoney = 0.25; - break; - case 4: //The Singularity - BitNodeMultipliers.ServerMaxMoney = 0.15; - BitNodeMultipliers.ServerStartingMoney = 0.75; - BitNodeMultipliers.ScriptHackMoney = 0.2; - BitNodeMultipliers.CompanyWorkMoney = 0.1; - BitNodeMultipliers.CrimeMoney = 0.2; - BitNodeMultipliers.HacknetNodeMoney = 0.05; - BitNodeMultipliers.CompanyWorkExpGain = 0.5; - BitNodeMultipliers.ClassGymExpGain = 0.5; - BitNodeMultipliers.FactionWorkExpGain = 0.5; - BitNodeMultipliers.HackExpGain = 0.4; - BitNodeMultipliers.CrimeExpGain = 0.5; - BitNodeMultipliers.FactionWorkRepGain = 0.75; - break; - case 5: //Artificial intelligence - BitNodeMultipliers.ServerMaxMoney = 2; - BitNodeMultipliers.ServerStartingSecurity = 2; - BitNodeMultipliers.ServerStartingMoney = 0.5; - BitNodeMultipliers.ScriptHackMoney = 0.15; - BitNodeMultipliers.HacknetNodeMoney = 0.2; - BitNodeMultipliers.CrimeMoney = 0.5; - BitNodeMultipliers.InfiltrationRep = 1.5; - BitNodeMultipliers.InfiltrationMoney = 1.5; - BitNodeMultipliers.AugmentationMoneyCost = 2; - BitNodeMultipliers.HackExpGain = 0.5; - BitNodeMultipliers.CorporationValuation = 0.5; - break; - case 6: //Bladeburner - BitNodeMultipliers.HackingLevelMultiplier = 0.5; - BitNodeMultipliers.ServerMaxMoney = 0.5; - BitNodeMultipliers.ServerStartingMoney = 0.5; - BitNodeMultipliers.ServerStartingSecurity = 1.5; - BitNodeMultipliers.ScriptHackMoney = 0.5; - BitNodeMultipliers.CompanyWorkMoney = 0.5; - BitNodeMultipliers.CrimeMoney = 0.5; - BitNodeMultipliers.InfiltrationMoney = 0.5; - BitNodeMultipliers.CorporationValuation = 0.2; - BitNodeMultipliers.HacknetNodeMoney = 0.2; - BitNodeMultipliers.FactionPassiveRepGain = 0; - BitNodeMultipliers.HackExpGain = 0.25; - break; - case 8: //Ghost of Wall Street - BitNodeMultipliers.ScriptHackMoney = 0; - BitNodeMultipliers.ManualHackMoney = 0; - BitNodeMultipliers.CompanyWorkMoney = 0; - BitNodeMultipliers.CrimeMoney = 0; - BitNodeMultipliers.HacknetNodeMoney = 0; - BitNodeMultipliers.InfiltrationMoney = 0; - BitNodeMultipliers.RepToDonateToFaction = 0; - BitNodeMultipliers.CorporationValuation = 0; - break; - case 11: //The Big Crash - BitNodeMultipliers.ServerMaxMoney = 0.1; - BitNodeMultipliers.ServerStartingMoney = 0.1; - BitNodeMultipliers.ServerGrowthRate = 0.5; - BitNodeMultipliers.ServerWeakenRate = 2; - BitNodeMultipliers.CrimeMoney = 3; - BitNodeMultipliers.CompanyWorkMoney = 0.5; - BitNodeMultipliers.HacknetNodeMoney = 0.1; - BitNodeMultipliers.AugmentationMoneyCost = 2; - BitNodeMultipliers.InfiltrationMoney = 2.5; - BitNodeMultipliers.InfiltrationRep = 2.5; - BitNodeMultipliers.CorporationValuation = 0.01; - break; - default: - console.log("WARNING: Player.bitNodeN invalid"); - break; - } -} - - - - -/***/ }), -/* 16 */ -/*!****************************!*\ - !*** ./utils/IPAddress.js ***! - \****************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRandomIp", function() { return createRandomIp; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ipExists", function() { return ipExists; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isValidIPAddress", function() { return isValidIPAddress; }); -/* harmony import */ var _src_Server_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Server.js */ 10); - -/* Functions to deal with manipulating IP addresses*/ - -//Generate a random IP address -//Will not return an IP address that already exists in the AllServers array -function createRandomIp() { - var ip = createRandomByte(99) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9); - - //If the Ip already exists, recurse to create a new one - if (ipExists(ip)) { - return createRandomIp(); - } - return ip; -} - -//Returns true if the IP already exists in one of the game's servers -function ipExists(ip) { - for (var property in _src_Server_js__WEBPACK_IMPORTED_MODULE_0__["AllServers"]) { - if (_src_Server_js__WEBPACK_IMPORTED_MODULE_0__["AllServers"].hasOwnProperty(property)) { - if (property == ip) { - return true; - } - } - } - return false; -} - -function createRandomByte(n=9) { - return Math.round(Math.random()*n); -} - -function isValidIPAddress(ipaddress) { - if (/^(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) - { - return true; - } - return false; -} - - - - -/***/ }), -/* 17 */ -/*!*********************************!*\ - !*** ./src/SpecialServerIps.js ***! - \*********************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerNames", function() { return SpecialServerNames; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIps", function() { return SpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIpsMap", function() { return SpecialServerIpsMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSpecialServerIps", function() { return loadSpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeSpecialServerIps", function() { return prestigeSpecialServerIps; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSpecialServerIps", function() { return initSpecialServerIps; }); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); - - -/* Holds IP of Special Servers */ -let SpecialServerNames = { - FulcrumSecretTechnologies: "Fulcrum Secret Technologies Server", - CyberSecServer: "CyberSec Server", - NiteSecServer: "NiteSec Server", - TheBlackHandServer: "The Black Hand Server", - BitRunnersServer: "BitRunners Server", - TheDarkArmyServer: "The Dark Army Server", - DaedalusServer: "Daedalus Server", - WorldDaemon: "w0r1d_d43m0n", -} -function SpecialServerIpsMap() {} - -SpecialServerIpsMap.prototype.addIp = function(name, ip) { - this[name] = ip; -} - -SpecialServerIpsMap.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Generic_toJSON"])("SpecialServerIpsMap", this); -} - -SpecialServerIpsMap.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Generic_fromJSON"])(SpecialServerIpsMap, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Reviver"].constructors.SpecialServerIpsMap = SpecialServerIpsMap; - -let SpecialServerIps = new SpecialServerIpsMap(); - -function prestigeSpecialServerIps() { - for (var member in SpecialServerIps) { - delete SpecialServerIps[member]; - } - SpecialServerIps = null; - SpecialServerIps = new SpecialServerIpsMap(); -} - -function loadSpecialServerIps(saveString) { - SpecialServerIps = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Reviver"]); -} - -function initSpecialServerIps() { - SpecialServerIps = new SpecialServerIpsMap(); -} - - - - -/***/ }), -/* 18 */ /*!*************************!*\ !*** ./src/Terminal.js ***! \*************************/ @@ -12760,29 +11060,29 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "post", function() { return post; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Terminal", function() { return Terminal; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KEY", function() { return KEY; }); -/* harmony import */ var _Alias_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias.js */ 30); +/* harmony import */ var _Alias_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias.js */ 25); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DarkWeb.js */ 35); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DarkWeb.js */ 82); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf.js */ 33); -/* harmony import */ var _HelpText_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./HelpText.js */ 71); -/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25); -/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Literature.js */ 53); -/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Message.js */ 29); -/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 6); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); +/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf.js */ 30); +/* harmony import */ var _HelpText_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./HelpText.js */ 67); +/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 21); +/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Literature.js */ 49); +/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Message.js */ 27); +/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./RedPill.js */ 45); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./TextFile.js */ 43); +/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./RedPill.js */ 41); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./TextFile.js */ 58); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/LogBox.js */ 51); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/LogBox.js */ 47); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); /* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! jszip */ 120); /* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_23__); /* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! file-saver */ 119); @@ -14817,10 +13117,354 @@ let Terminal = { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 19 */ +/* 16 */ +/*!*********************************!*\ + !*** ./src/SpecialServerIps.js ***! + \*********************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerNames", function() { return SpecialServerNames; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIps", function() { return SpecialServerIps; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpecialServerIpsMap", function() { return SpecialServerIpsMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSpecialServerIps", function() { return loadSpecialServerIps; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeSpecialServerIps", function() { return prestigeSpecialServerIps; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSpecialServerIps", function() { return initSpecialServerIps; }); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); + + +/* Holds IP of Special Servers */ +let SpecialServerNames = { + FulcrumSecretTechnologies: "Fulcrum Secret Technologies Server", + CyberSecServer: "CyberSec Server", + NiteSecServer: "NiteSec Server", + TheBlackHandServer: "The Black Hand Server", + BitRunnersServer: "BitRunners Server", + TheDarkArmyServer: "The Dark Army Server", + DaedalusServer: "Daedalus Server", + WorldDaemon: "w0r1d_d43m0n", +} +function SpecialServerIpsMap() {} + +SpecialServerIpsMap.prototype.addIp = function(name, ip) { + this[name] = ip; +} + +SpecialServerIpsMap.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Generic_toJSON"])("SpecialServerIpsMap", this); +} + +SpecialServerIpsMap.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Generic_fromJSON"])(SpecialServerIpsMap, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Reviver"].constructors.SpecialServerIpsMap = SpecialServerIpsMap; + +let SpecialServerIps = new SpecialServerIpsMap(); + +function prestigeSpecialServerIps() { + for (var member in SpecialServerIps) { + delete SpecialServerIps[member]; + } + SpecialServerIps = null; + SpecialServerIps = new SpecialServerIpsMap(); +} + +function loadSpecialServerIps(saveString) { + SpecialServerIps = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_0__["Reviver"]); +} + +function initSpecialServerIps() { + SpecialServerIps = new SpecialServerIpsMap(); +} + + + + +/***/ }), +/* 17 */ +/*!******************************!*\ + !*** ./src/CreateProgram.js ***! + \******************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Programs", function() { return Programs; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayCreateProgramContent", function() { return displayCreateProgramContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getNumAvailableCreateProgram", function() { return getNumAvailableCreateProgram; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initCreateProgramButtons", function() { return initCreateProgramButtons; }); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); + + + + +/* Create programs */ +let Programs = { + NukeProgram: "NUKE.exe", + BruteSSHProgram: "BruteSSH.exe", + FTPCrackProgram: "FTPCrack.exe", + RelaySMTPProgram: "relaySMTP.exe", + HTTPWormProgram: "HTTPWorm.exe", + SQLInjectProgram: "SQLInject.exe", + DeepscanV1: "DeepscanV1.exe", + DeepscanV2: "DeepscanV2.exe", + ServerProfiler: "ServerProfiler.exe", + AutoLink: "AutoLink.exe", + Flight: "fl1ght.exe", + BitFlume: "b1t_flum3.exe" +}; + +var nukeALink, bruteSshALink, ftpCrackALink, relaySmtpALink, httpWormALink, sqlInjectALink, + deepscanv1ALink, deepscanv2ALink, servProfilerALink, autolinkALink, bitFlumeALink; +function displayCreateProgramContent() { + nukeALink.style.display = "none"; + bruteSshALink.style.display = "none"; + ftpCrackALink.style.display = "none"; + relaySmtpALink.style.display = "none"; + httpWormALink.style.display = "none"; + sqlInjectALink.style.display = "none"; + deepscanv1ALink.style.display = "none"; + deepscanv2ALink.style.display = "none"; + servProfilerALink.style.display = "none"; + autolinkALink.style.display = "none"; + bitFlumeALink.style.display = "none"; + + //NUKE.exe (in case you delete it lol) + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) { + nukeALink.style.display = "inline-block"; + } + //BruteSSH + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 50) { + bruteSshALink.style.display = "inline-block"; + } + //FTPCrack + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 100) { + ftpCrackALink.style.display = "inline-block"; + } + //relaySMTP + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 250) { + relaySmtpALink.style.display = "inline-block"; + } + //HTTPWorm + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 500) { + httpWormALink.style.display = "inline-block"; + } + //SQLInject + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 750) { + sqlInjectALink.style.display = "inline-block"; + } + //Deepscan V1 and V2 + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV1) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { + deepscanv1ALink.style.display = "inline-block"; + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV2) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 400) { + deepscanv2ALink.style.display = "inline-block"; + } + //Server profiler + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.ServerProfiler) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { + servProfilerALink.style.display = "inline-block"; + } + //Auto Link + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.AutoLink) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 25) { + autolinkALink.style.display = "inline-block"; + } + //Bit Flume + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.BitFlume) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].sourceFiles.length > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 5) { + bitFlumeALink.style.display = "inline-block"; + } +} + +//Returns the number of programs that are currently available to be created +function getNumAvailableCreateProgram() { + var count = 0; + //PortHack.exe (in case you delete it lol) + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) { + ++count; + } + //BruteSSH + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 50) { + ++count; + } + //FTPCrack + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 100) { + ++count; + } + //relaySMTP + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 250) { + ++count; + } + //HTTPWorm + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 500) { + ++count; + } + //SQLInject + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 && + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 750) { + ++count; + } + //Deepscan V1 and V2 + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV1) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { + ++count; + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.DeepscanV2) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 400) { + ++count; + } + //Server profiler + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.ServerProfiler) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 75) { + ++count; + } + //Auto link + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.AutoLink) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 25) { + ++count; + } + //Bit Flume + if (!_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hasProgram(Programs.BitFlume) && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].sourceFiles.length > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill >= 5) { + ++count; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable === false && count > 0) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].firstProgramAvailable = true; + document.getElementById("create-program-tab").style.display = "list-item"; + document.getElementById("hacking-menu-header").click(); + document.getElementById("hacking-menu-header").click(); + } + return count; +} + +function initCreateProgramButtons() { + var createProgramList = document.getElementById("create-program-list"); + nukeALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-nuke", innerText:Programs.NukeProgram, + tooltip:"This virus is used to gain root access to a machine if enough ports are opened.", + }); + createProgramList.appendChild(nukeALink); + + bruteSshALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-brutessh", innerText:Programs.BruteSSHProgram, + tooltip:"This program executes a brute force attack that opens SSH ports" + }); + createProgramList.appendChild(bruteSshALink); + + ftpCrackALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-ftpcrack", innerText:Programs.FTPCrackProgram, + tooltip:"This program cracks open FTP ports" + }); + createProgramList.appendChild(ftpCrackALink); + + relaySmtpALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-relaysmtp", innerText:Programs.RelaySMTPProgram, + tooltip:"This program opens SMTP ports by redirecting data" + }) ; + createProgramList.appendChild(relaySmtpALink); + + httpWormALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-httpworm", innerText:Programs.HTTPWormProgram, + tooltip:"This virus opens up HTTP ports" + }); + createProgramList.appendChild(httpWormALink); + + sqlInjectALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-sqlinject", innerText:Programs.SQLInjectProgram, + tooltip:"This virus opens SQL ports" + }); + createProgramList.appendChild(sqlInjectALink); + + deepscanv1ALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-deepscanv1", innerText:Programs.DeepscanV1, + tooltip:"This program allows you to use the scan-analyze command with a depth up to 5" + }); + createProgramList.appendChild(deepscanv1ALink); + + deepscanv2ALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-deepscanv2", innerText:Programs.DeepscanV2, + tooltip:"This program allows you to use the scan-analyze command with a depth up to 10" + }); + createProgramList.appendChild(deepscanv2ALink); + + servProfilerALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-serverprofiler", innerText:Programs.ServerProfiler, + tooltip:"This program is used to display hacking and Netscript-related information about servers" + }); + createProgramList.appendChild(servProfilerALink); + + bitFlumeALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-bitflume", innerText:Programs.BitFlume, + tooltip:"This program creates a portal to the BitNode Nexus (allows you to restart and switch BitNodes)" + }); + createProgramList.appendChild(bitFlumeALink); + + autolinkALink = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_2__["createElement"])("a", { + class:"a-link-button", id:"create-program-autolink", innerText:"AutoLink.exe", + tooltip:"This program allows you to directly connect to other servers through the 'scan-analyze' command" + }); + createProgramList.appendChild(autolinkALink); + + nukeALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.NukeProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes, 1); + return false; + }); + bruteSshALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.BruteSSHProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes * 2, 50); + return false; + }); + ftpCrackALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.FTPCrackProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour, 100); + return false; + }); + relaySmtpALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.RelaySMTPProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours, 250); + return false; + }); + httpWormALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.HTTPWormProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer4Hours, 500); + return false; + }); + sqlInjectALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.SQLInjectProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer8Hours, 750); + return false; + }); + deepscanv1ALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.DeepscanV1, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour, 75); + return false; + }); + deepscanv2ALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.DeepscanV2, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPer2Hours, 400); + return false; + }); + servProfilerALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.ServerProfiler, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerHalfHour, 75); + return false; + }); + autolinkALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.AutoLink, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerQuarterHour, 25); + return false; + }); + bitFlumeALink.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCreateProgramWork(Programs.BitFlume, _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MillisecondsPerFiveMinutes / 5, 5); + return false; + }); +} + + + + +/***/ }), +/* 18 */ /*!******************************!*\ !*** ./src/Augmentations.js ***! \******************************/ @@ -14837,21 +13481,21 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "augmentationExists", function() { return augmentationExists; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Augmentation", function() { return Augmentation; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayAugmentationsContent", function() { return displayAugmentationsContent; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Prestige.js */ 57); -/* harmony import */ var _SaveObject_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./SaveObject.js */ 47); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SourceFile.js */ 44); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Prestige.js */ 53); +/* harmony import */ var _SaveObject_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./SaveObject.js */ 43); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SourceFile.js */ 37); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); @@ -17460,2052 +16104,7 @@ function displaySourceFiles(listElement, sourceFiles) { /***/ }), -/* 20 */ -/*!***********************!*\ - !*** ./src/Crimes.js ***! - \***********************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitShopliftCrime", function() { return commitShopliftCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitRobStoreCrime", function() { return commitRobStoreCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitMugCrime", function() { return commitMugCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitLarcenyCrime", function() { return commitLarcenyCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitDealDrugsCrime", function() { return commitDealDrugsCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitBondForgeryCrime", function() { return commitBondForgeryCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitTraffickArmsCrime", function() { return commitTraffickArmsCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitHomicideCrime", function() { return commitHomicideCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitGrandTheftAutoCrime", function() { return commitGrandTheftAutoCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitKidnapCrime", function() { return commitKidnapCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitAssassinationCrime", function() { return commitAssassinationCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "commitHeistCrime", function() { return commitHeistCrime; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeSuccess", function() { return determineCrimeSuccess; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceShoplift", function() { return determineCrimeChanceShoplift; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceRobStore", function() { return determineCrimeChanceRobStore; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceMug", function() { return determineCrimeChanceMug; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceLarceny", function() { return determineCrimeChanceLarceny; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceDealDrugs", function() { return determineCrimeChanceDealDrugs; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceBondForgery", function() { return determineCrimeChanceBondForgery; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceTraffickArms", function() { return determineCrimeChanceTraffickArms; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceHomicide", function() { return determineCrimeChanceHomicide; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceGrandTheftAuto", function() { return determineCrimeChanceGrandTheftAuto; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceKidnap", function() { return determineCrimeChanceKidnap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceAssassination", function() { return determineCrimeChanceAssassination; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeChanceHeist", function() { return determineCrimeChanceHeist; }); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); - - - - -/* Crimes.js */ -function commitShopliftCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift; - var time = 2000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 0, 0, 2/div, 2/div, 0, 15000/div, time, singParams); //$7500/s, 1 exp/s - return time; -} - -function commitRobStoreCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore; - var time = 60000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(30/div, 0, 0, 45/div, 45/div, 0, 400000/div, time, singParams); //$6666,6/2, 0.5exp/s, 0.75exp/s - return time; -} - -function commitMugCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug; - var time = 4000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 3/div, 3/div, 3/div, 3/div, 0, 36000/div, time, singParams); //$9000/s, .66 exp/s - return time; -} - -function commitLarcenyCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny; - var time = 90000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(45/div, 0, 0, 60/div, 60/div, 0, 800000/div, time, singParams) // $8888.88/s, .5 exp/s, .66 exp/s - return time; -} - -function commitDealDrugsCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs; - var time = 10000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 0, 0, 5/div, 5/div, 10/div, 120000/div, time, singParams); //$12000/s, .5 exp/s, 1 exp/s - return time; -} - -function commitBondForgeryCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery; - var time = 300000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(100/div, 0, 0, 150/div, 0, 15/div, 4500000/div, time, singParams); //$15000/s, 0.33 hack exp/s, .5 dex exp/s, .05 cha exp - return time; -} - -function commitTraffickArmsCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms; - var time = 40000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 20/div, 20/div, 20/div, 20/div, 40/div, 600000/div, time, singParams); //$15000/s, .5 combat exp/s, 1 cha exp/s - return time; -} - -function commitHomicideCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide; - var time = 3000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 2/div, 2/div, 2/div, 2/div, 0, 45000/div, time, singParams); //$15000/s, 0.66 combat exp/s - return time; -} - -function commitGrandTheftAutoCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto; - var time = 80000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 20/div, 20/div, 20/div, 80/div, 40/div, 1600000/div, time, singParams); //$20000/s, .25 exp/s, 1 exp/s, .5 exp/s - return time; -} - -function commitKidnapCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap; - var time = 120000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 80/div, 80/div, 80/div, 80/div, 80/div, 3600000/div, time, singParams); //$30000/s. .66 exp/s - return time; -} - -function commitAssassinationCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination; - var time = 300000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(0, 300/div, 300/div, 300/div, 300/div, 0, 12000000/div, time, singParams); //$40000/s, 1 exp/s - return time; -} - -function commitHeistCrime(div=1, singParams=null) { - if (div <= 0) {div = 1;} - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist; - var time = 600000; - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime(450/div, 450/div, 450/div, 450/div, 450/div, 450/div, 120000000/div, time, singParams); //$200000/s, .75exp/s - return time; -} - -function determineCrimeSuccess(crime, moneyGained) { - var chance = 0; - switch (crime) { - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift: - chance = determineCrimeChanceShoplift(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore: - chance = determineCrimeChanceRobStore(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug: - chance = determineCrimeChanceMug(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny: - chance = determineCrimeChanceLarceny(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs: - chance = determineCrimeChanceDealDrugs(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery: - chance = determineCrimeChanceBondForgery(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms: - chance = determineCrimeChanceTraffickArms(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide: - chance = determineCrimeChanceHomicide(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto: - chance = determineCrimeChanceGrandTheftAuto(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap: - chance = determineCrimeChanceKidnap(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination: - chance = determineCrimeChanceAssassination(); - break; - case _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist: - chance = determineCrimeChanceHeist(); - break; - default: - console.log(crime); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); - return; - } - - if (Math.random() <= chance) { - //Success - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].gainMoney(moneyGained); - return true; - } else { - //Failure - return false; - } -} - -let intWgt = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeWeight; -let maxLvl = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; - -function determineCrimeChanceShoplift() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 20; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceRobStore() { - var chance = (0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl + - 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - 1 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 5; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceMug() { - var chance = (1.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl + - 1.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 5; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceLarceny() { - var chance = (0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) * 3; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceDealDrugs() { - var chance = (3*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl + - 2*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl); - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceBondForgery() { - var chance = (0.1*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl + - 2.5*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - 2*intWgt*_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl); - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceTraffickArms() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 2; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceHomicide() { - var chance = (2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl + - 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - 0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl); - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceGrandTheftAuto() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - 4 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 8; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceKidnap() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 5; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceAssassination() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - 2 * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 8; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - -function determineCrimeChanceHeist() { - var chance = (_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility / maxLvl + - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma / maxLvl + - intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence / maxLvl) / 18; - chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; - return Math.min(chance, 1); -} - - - - -/***/ }), -/* 21 */ -/*!********************************!*\ - !*** ./src/NetscriptWorker.js ***! - \********************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkerScript", function() { return WorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workerScripts", function() { return workerScripts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPorts", function() { return NetscriptPorts; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptsLoop", function() { return runScriptsLoop; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killWorkerScript", function() { return killWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWorkerScript", function() { return addWorkerScript; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateOnlineScriptTimes", function() { return updateOnlineScriptTimes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeWorkerScripts", function() { return prestigeWorkerScripts; }); -/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 41); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 69); -/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 6); -/* harmony import */ var _NetscriptJSEvaluator_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptJSEvaluator.js */ 63); -/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptPort.js */ 46); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/acorn.js */ 36); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); - - - - - - - - - - - - - - -function WorkerScript(runningScriptObj) { - this.name = runningScriptObj.filename; - this.running = false; - this.serverIp = null; - this.code = runningScriptObj.scriptRef.code; - this.env = new _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__["Environment"](this); - this.env.set("args", runningScriptObj.args.slice()); - this.output = ""; - this.ramUsage = 0; - this.scriptRef = runningScriptObj; - this.errorMessage = ""; - this.args = runningScriptObj.args.slice(); - this.delay = null; - this.fnWorker = null; //Workerscript for a function call - this.checkingRam = false; - this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM - this.disableLogs = {}; //Stores names of fns that should have logs disabled -} - -//Returns the server on which the workerScript is running -WorkerScript.prototype.getServer = function() { - return _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][this.serverIp]; -} - -//Returns the Script object for the underlying script -WorkerScript.prototype.getScript = function() { - let server = this.getServer(); - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename === this.name) { - return server.scripts[i]; - } - } - console.log("ERROR: Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong"); - return null; -} - -//Array containing all scripts that are running across all servers, to easily run them all -let workerScripts = []; - -var NetscriptPorts = []; -for (var i = 0; i < _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NumNetscriptPorts; ++i) { - NetscriptPorts.push(new _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_6__["NetscriptPort"]()); -} - -function prestigeWorkerScripts() { - for (var i = 0; i < workerScripts.length; ++i) { - Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); - workerScripts[i].env.stopFlag = true; - } - Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])(5000); //Force UI to update - workerScripts.length = 0; -} - -// JS script promises need a little massaging to have the same guarantees as netscript -// promises. This does said massaging and kicks the script off. It returns a promise -// that resolves or rejects when the corresponding worker script is done. -function startJsScript(workerScript) { - workerScript.running = true; - - // The name of the currently running netscript function, to prevent concurrent - // calls to hack, grow, etc. - let runningFn = null; - - // We need to go through the environment and wrap each function in such a way that it - // can be called at most once at a time. This will prevent situations where multiple - // hack promises are outstanding, for example. - function wrap(propName, f) { - // This function unfortunately cannot be an async function, because we don't - // know if the original one was, and there's no way to tell. - return function (...args) { - // Wrap every netscript function with a check for the stop flag. - // This prevents cases where we never stop because we are only calling - // netscript functions that don't check this. - // This is not a problem for legacy Netscript because it also checks the - // stop flag in the evaluator. - if (workerScript.env.stopFlag) {throw workerScript;} - - if (propName === "sleep") return f(...args); // OK for multiple simultaneous calls to sleep. - - const msg = "Concurrent calls to Netscript functions not allowed! " + - "Did you forget to await hack(), grow(), or some other " + - "promise-returning function? (Currently running: %s tried to run: %s)" - if (runningFn) { - workerScript.errorMessage = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])(workerScript, sprintf(msg, runningFn, propName), null) - throw workerScript; - } - runningFn = propName; - let result = f(...args); - if (result && result.finally !== undefined) { - return result.finally(function () { - runningFn = null; - }); - } else { - runningFn = null; - return result; - } - } - }; - - for (let prop in workerScript.env.vars) { - if (typeof workerScript.env.vars[prop] !== "function") continue; - workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]); - } - - // Note: the environment that we pass to the JS script only needs to contain the functions visible - // to that script, which env.vars does at this point. - return Object(_NetscriptJSEvaluator_js__WEBPACK_IMPORTED_MODULE_5__["executeJSScript"])(workerScript.getServer().scripts, - workerScript).then(function (mainReturnValue) { - if (mainReturnValue === undefined) return workerScript; - return [mainReturnValue, workerScript]; - }).catch(e => { - if (e instanceof Error) { - workerScript.errorMessage = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])( - workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || "")); - throw workerScript; - } else if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(e)) { - workerScript.errorMessage = e; - throw workerScript; - } - throw e; // Don't know what to do with it, let's rethrow. - }); -} - -//Loop through workerScripts and run every script that is not currently running -function runScriptsLoop() { - var scriptDeleted = false; - - //Delete any scripts that finished or have been killed. Loop backwards bc removing items screws up indexing - for (var i = workerScripts.length - 1; i >= 0; i--) { - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { - scriptDeleted = true; - //Delete script from the runningScripts array on its host serverIp - var ip = workerScripts[i].serverIp; - var name = workerScripts[i].name; - - //Free RAM - _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].ramUsed -= workerScripts[i].ramUsage; - - //Delete script from Active Scripts - Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); - - for (var j = 0; j < _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.length; j++) { - if (_Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].filename == name && - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(_Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].args, workerScripts[i].args)) { - _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.splice(j, 1); - break; - } - } - - //Delete script from workerScripts - workerScripts.splice(i, 1); - } - } - if (scriptDeleted) {Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])();} //Force Update - - - //Run any scripts that haven't been started - for (var i = 0; i < workerScripts.length; i++) { - //If it isn't running, start the script - if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { - let p = null; // p is the script's result promise. - if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) { - p = startJsScript(workerScripts[i]); - } else { - try { - var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__["parse"])(workerScripts[i].code, {sourceType:"module"}); - //console.log(ast); - } catch (e) { - console.log("Error parsing script: " + workerScripts[i].name); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Syntax ERROR in " + workerScripts[i].name + ":
" + e); - workerScripts[i].env.stopFlag = true; - continue; - } - workerScripts[i].running = true; - p = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["evaluate"])(ast, workerScripts[i]); - } - - //Once the code finishes (either resolved or rejected, doesnt matter), set its - //running status to false - p.then(function(w) { - console.log("Stopping script " + w.name + " because it finished running naturally"); - w.running = false; - w.env.stopFlag = true; - w.scriptRef.log("Script finished running"); - }).catch(function(w) { - if (w instanceof Error) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { - //Script ends with a return statement - console.log("Script returning with value: " + w[1]); - //TODO maybe do something with this in the future - return; - } else if (w instanceof WorkerScript) { - if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w.errorMessage)) { - var errorTextArray = w.errorMessage.split("|"); - if (errorTextArray.length != 4) { - console.log("ERROR: Something wrong with Error text in evaluator..."); - console.log("Error text: " + errorText); - return; - } - var serverIp = errorTextArray[1]; - var scriptName = errorTextArray[2]; - var errorMsg = errorTextArray[3]; - - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime error:
Server Ip: " + serverIp + - "
Script name: " + scriptName + - "
Args:" + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["printArray"])(w.args) + "
" + errorMsg); - w.scriptRef.log("Script crashed with runtime error"); - } else { - w.scriptRef.log("Script killed"); - } - w.running = false; - w.env.stopFlag = true; - - } else if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); - console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); - return; - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev"); - console.log(w); - } - }); - } - } - - setTimeout(runScriptsLoop, 6000); -} - -//Queues a script to be killed by settings its stop flag to true. Then, the code will reject -//all of its promises recursively, and when it does so it will no longer be running. -//The runScriptsLoop() will then delete the script from worker scripts -function killWorkerScript(runningScriptObj, serverIp) { - for (var i = 0; i < workerScripts.length; i++) { - if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) { - workerScripts[i].env.stopFlag = true; - Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(workerScripts[i]); - //Recursively kill all functions - var curr = workerScripts[i]; - while (curr.fnWorker) { - curr.fnWorker.env.stopFlag = true; - Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(curr.fnWorker); - curr = curr.fnWorker; - } - return true; - } - } - return false; -} - -//Queues a script to be run -function addWorkerScript(runningScriptObj, server) { - var filename = runningScriptObj.filename; - - //Update server's ram usage - var threads = 1; - if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { - threads = runningScriptObj.threads; - } else { - runningScriptObj.threads = 1; - } - var ramUsage = runningScriptObj.scriptRef.ramUsage * threads - * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, threads-1); - var ramAvailable = server.maxRam - server.ramUsed; - if (ramUsage > ramAvailable) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["printArray"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + - "the game and the script's RAM usage increased (either because of an update to the game or " + - "your changes to the script.)"); - return; - } - server.ramUsed += ramUsage; - - //Create the WorkerScript - var s = new WorkerScript(runningScriptObj); - s.serverIp = server.ip; - s.ramUsage = ramUsage; - - //Add the WorkerScript to the Active Scripts list - Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["addActiveScriptsItem"])(s); - - //Add the WorkerScript - workerScripts.push(s); - return; -} - -//Updates the online running time stat of all running scripts -function updateOnlineScriptTimes(numCycles = 1) { - var time = (numCycles * _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed) / 1000; //seconds - for (var i = 0; i < workerScripts.length; ++i) { - workerScripts[i].scriptRef.onlineRunningTime += time; - } -} - - - - -/***/ }), -/* 22 */ -/*!****************************!*\ - !*** ./src/StockMarket.js ***! - \****************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockMarket", function() { return StockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockSymbols", function() { return StockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolToStockMap", function() { return SymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockSymbols", function() { return initStockSymbols; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockMarket", function() { return initStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSymbolToStockMap", function() { return initSymbolToStockMap; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stockMarketCycle", function() { return stockMarketCycle; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyStock", function() { return buyStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellStock", function() { return sellStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shortStock", function() { return shortStock; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellShort", function() { return sellShort; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPrices", function() { return updateStockPrices; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayStockMarketContent", function() { return displayStockMarketContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockTicker", function() { return updateStockTicker; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPlayerPosition", function() { return updateStockPlayerPosition; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadStockMarket", function() { return loadStockMarket; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStockMarketContentCreated", function() { return setStockMarketContentCreated; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "placeOrder", function() { return placeOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cancelOrder", function() { return cancelOrder; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Order", function() { return Order; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderTypes", function() { return OrderTypes; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionTypes", function() { return PositionTypes; }); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); - - - - - - - - - - - - - - -let StockPriceCap = 1e9; //Put a limit on how high a price can go - -function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) { - this.symbol = symbol; - this.name = name; - this.price = initPrice; - - this.playerShares = 0; - this.playerAvgPx = 0; - this.playerShortShares = 0; - this.playerAvgShortPx = 0; - this.mv = mv; - this.b = b; - this.otlkMag = otlkMag; - - this.posTxtEl = null; -} - -Stock.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Stock", this); -} - -Stock.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Stock, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Stock = Stock; - -var OrderTypes = { - LimitBuy: "Limit Buy Order", - LimitSell: "Limit Sell Order", - StopBuy: "Stop Buy Order", - StopSell: "Stop Sell Order" -} - -var PositionTypes = { - Long: "L", - Short: "S" -} - -function placeOrder(stock, shares, price, type, position, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - var order = new Order(stock, shares, price, type, position); - if (isNaN(shares) || isNaN(price)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); - } - return false; - } - if (StockMarket["Orders"] == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - StockMarket["Orders"][stock.symbol].push(order); - //Process to see if it should be executed immediately - processOrders(order.stock, order.type, order.pos); - updateStockOrderList(order.stock); - return true; -} - -//Returns true if successfully cancels an order, false otherwise -function cancelOrder(params, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (StockMarket["Orders"] == null) {return false;} - if (params.order && params.order instanceof Order) { - var order = params.order; - //An 'Order' object is passed in - var stockOrders = StockMarket["Orders"][order.stock.symbol]; - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return true; - } - } - return false; - } else if (params.stock && params.shares && params.price && params.type && - params.pos && params.stock instanceof Stock) { - //Order properties are passed in. Need to look for the order - var stockOrders = StockMarket["Orders"][params.stock.symbol]; - var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(params.price).format('$0.000a'); - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (params.shares === order.shares && - params.price === order.price && - params.type === order.type && - params.pos === order.pos) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - if (tixApi) { - workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); - } - return true; - } - } - if (tixApi) { - workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); - } - return false; - } - return false; -} - -function executeOrder(order) { - var stock = order.stock; - var orderBook = StockMarket["Orders"]; - var stockOrders = orderBook[stock.symbol]; - var res = true; - console.log("Executing the following order:"); - console.log(order); - switch (order.type) { - case OrderTypes.LimitBuy: - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long) { - res = buyStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = shortStock(order.stock, order.shares) && res; - } - break; - case OrderTypes.LimitSell: - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long) { - res = sellStock(order.stock, order.shares) && res; - } else if (order.pos === PositionTypes.Short) { - res = sellShort(order.stock, order.shares) && res; - } - break; - } - if (res) { - //Remove order from order book - for (var i = 0; i < stockOrders.length; ++i) { - if (order == stockOrders[i]) { - stockOrders.splice(i, 1); - updateStockOrderList(order.stock); - return; - } - } - console.log("ERROR: Could not find the following Order in Order Book: "); - console.log(order); - } else { - console.log("Order failed to execute"); - } -} - -function Order(stock, shares, price, type, position) { - this.stock = stock; - this.shares = shares; - this.price = price; - this.type = type; - this.pos = position; -} - -Order.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Order", this); -} - -Order.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Order, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Order = Order; - -let StockMarket = {} //Full name to stock object -let StockSymbols = {} //Full name to symbol -let SymbolToStockMap = {}; //Symbol to Stock object - -function loadStockMarket(saveString) { - if (saveString === "") { - StockMarket = {}; - } else { - StockMarket = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"]); - } -} - -function initStockSymbols() { - //Stocks for companies at which you can work - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp] = "ECP"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp] = "MGCP"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries] = "BLD"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated] = "CLRK"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated] = "OMTK"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma] = "FSIG"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational] = "KGI"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies] = "FLCM"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies] = "STM"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm] = "DCOMM"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs] = "HLS"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife] = "VITA"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems] = "ICRS"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy] = "UNV"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp] = "AERO"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems] = "OMN"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical] = "NVMD"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity] = "WDS"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp] = "LXO"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction] = "RHOC"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises] = "APHE"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities] = "SYSC"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek] = "CTK"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies] = "NTLK"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware] = "OMGA"; - StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff] = "FNS"; - - //Stocks for other companies - StockSymbols["Sigma Cosmetics"] = "SGC"; - StockSymbols["Joes Guns"] = "JGN"; - StockSymbols["Catalyst Ventures"] = "CTYS"; - StockSymbols["Microdyne Technologies"] = "MDYN"; - StockSymbols["Titan Laboratories"] = "TITN"; -} - -function initStockMarket() { - for (var stk in StockMarket) { - if (StockMarket.hasOwnProperty(stk)) { - delete StockMarket[stk]; - } - } - - var ecorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp; - var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[ecorp] = ecorpStk; - - var megacorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp; - var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(25000, 33000)); - StockMarket[megacorp] = megacorpStk; - - var blade = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries; - var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 22000)); - StockMarket[blade] = bladeStk; - - var clarke = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated; - var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); - StockMarket[clarke] = clarkeStk; - - var omnitek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated; - var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(35000, 40000)); - StockMarket[omnitek] = omnitekStk; - - var foursigma = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma; - var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(60000, 70000)); - StockMarket[foursigma] = foursigmaStk; - - var kuaigong = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational; - var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 24000)); - StockMarket[kuaigong] = kuaigongStk; - - var fulcrum = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies; - var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30000, 35000)); - StockMarket[fulcrum] = fulcrumStk; - - var storm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies; - var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(21000, 24000)); - StockMarket[storm] = stormStk; - - var defcomm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm; - var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); - StockMarket[defcomm] = defcommStk; - - var helios = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs; - var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(12000, 16000)); - StockMarket[helios] = heliosStk; - - var vitalife = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife; - var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 12000)); - StockMarket[vitalife] = vitalifeStk; - - var icarus = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems; - var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(16000, 20000)); - StockMarket[icarus] = icarusStk; - - var universalenergy = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy; - var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[universalenergy] = universalenergyStk; - - var aerocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp; - var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); - StockMarket[aerocorp] = aerocorpStk; - - var omnia = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems; - var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(9000, 12000)); - StockMarket[omnia] = omniaStk; - - var solaris = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems; - var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[solaris] = solarisStk; - - var globalpharm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals; - var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[globalpharm] = globalpharmStk; - - var nova = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical; - var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); - StockMarket[nova] = novaStk; - - var watchdog = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity; - var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[watchdog] = watchdogStk; - - var lexocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp; - var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[lexocorp] = lexocorpStk; - - var rho = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction; - var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); - StockMarket[rho] = rhoStk; - - var alpha = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises; - var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); - StockMarket[alpha] = alphaStk; - - var syscore = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities; - var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(4000, 7000)) - StockMarket[syscore] = syscoreStk; - - var computek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek; - var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 5000)); - StockMarket[computek] = computekStk; - - var netlink = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies; - var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 4000)); - StockMarket[netlink] = netlinkStk; - - var omega = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware; - var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); - StockMarket[omega] = omegaStk; - - var fns = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff; - var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(1000, 4000)); - StockMarket[fns] = fnsStk; - - var sigmacosm = "Sigma Cosmetics"; - var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 3000)); - StockMarket[sigmacosm] = sigmacosmStk; - - var joesguns = "Joes Guns"; - var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); - StockMarket[joesguns] = joesgunsStk; - - var catalyst = "Catalyst Ventures"; - var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); - StockMarket[catalyst] = catalystStk; - - var microdyne = "Microdyne Technologies"; - var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); - StockMarket[microdyne] = microdyneStk; - - var titanlabs = "Titan Laboratories"; - var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); - StockMarket[titanlabs] = titanlabsStk; - - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; -} - -function initSymbolToStockMap() { - for (var name in StockSymbols) { - if (StockSymbols.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (stock == null) { - console.log("ERROR finding stock"); - continue; - } - var symbol = StockSymbols[name]; - SymbolToStockMap[symbol] = stock; - } - } -} - -function stockMarketCycle() { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - var thresh = 0.6; - if (stock.b) {thresh = 0.4;} - if (Math.random() < thresh) { - stock.b = !stock.b; - } - } - } -} - -//Returns true if successful, false otherwise -function buyStock(stock, shares) { - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to buy stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares == 0) {return false;} - - var totalPrice = stock.price * shares; - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2).toString() + "."); - return false; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - updateStockPlayerPosition(stock); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); - return true; -} - -//Returns true if successful and false otherwise -function sellStock(stock, shares) { - if (shares == 0) {return false;} - if (stock == null || shares < 0 || isNaN(shares)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell stock. This may be a bug, contact developer"); - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return false;} - var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(gains); - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - updateStockPlayerPosition(stock); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gains, 2)); - return true; -} - -//Returns true if successful and false otherwise -function shortStock(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to initiate a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares === 0) {return false;} - - var totalPrice = stock.price * shares; - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " + - "money to purchase this short position. You need " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)')); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + "."); - } - - return false; - } - - var origTotal = stock.playerShortShares * stock.playerAvgShortPx; - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShortShares += shares; - stock.playerAvgShortPx = newTotal / stock.playerShortShares; - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) { - workerScript.scriptRef.log("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. Paid " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)') + " in commission fees."); - } - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); - } - return true; -} - -//Returns true if successful and false otherwise -function sellShort(stock, shares, workerScript=null) { - var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); - if (stock == null || isNaN(shares) || shares < 0) { - if (tixApi) { - workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell a short position in a stock. This is probably " + - "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); - } - return false; - } - shares = Math.round(shares); - if (shares > stock.playerShortShares) {shares = stock.playerShortShares;} - if (shares === 0) {return false;} - - var origCost = shares * stock.playerAvgShortPx; - var profit = ((stock.playerAvgShortPx - stock.price) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; - if (isNaN(profit)) {profit = 0;} - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(origCost + profit); - if (tixApi) { - workerScript.scriptRef.onlineMoneyMade += profit; - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].scriptProdSinceLastAug += profit; - } - - stock.playerShortShares -= shares; - if (stock.playerShortShares === 0) { - stock.playerAvgShortPx = 0; - } - updateStockPlayerPosition(stock); - if (tixApi) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) { - workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " + - "a total of " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(origCost + profit).format('($0.000a)')); - } - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + - "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(origCost + profit, 2)); - } - - return true; -} - -function updateStockPrices() { - var v = Math.random(); - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - var av = (v * stock.mv) / 100; - if (isNaN(av)) {av = .02;} - - var chc = 50; - if (stock.b) { - chc = (chc + stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } else { - chc = (chc - stock.otlkMag)/100; - if (isNaN(chc)) {chc = 0.5;} - } - if (stock.price >= StockPriceCap) { - chc = -1; //Limit on stock price - stock.b = false; - } - - var c = Math.random(); - if (c < chc) { - stock.price *= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { - updateStockTicker(stock, true); - } - } else { - stock.price /= (1 + av); - processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); - processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); - processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); - processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { - updateStockTicker(stock, false); - } - } - - var otlkMagChange = stock.otlkMag * av; - if (stock.otlkMag <= 0.1) { - otlkMagChange = 1; - } - if (c < 0.5) { - stock.otlkMag += otlkMagChange; - } else { - stock.otlkMag -= otlkMagChange; - } - if (stock.otlkMag < 0) { - stock.otlkMag *= -1; - stock.b = !stock.b; - } - - } - } -} - -//Checks and triggers any orders for the specified stock -function processOrders(stock, orderType, posType) { - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - return; //Newly created, so no orders to process - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null || !(stockOrders.constructor === Array)) { - console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); - stockOrders = []; - return; - } - for (var i = 0; i < stockOrders.length; ++i) { - var order = stockOrders[i]; - if (order.type === orderType && order.pos === posType) { - switch(order.type) { - case OrderTypes.LimitBuy: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.LimitSell: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopBuy: - if (order.pos === PositionTypes.Long && stock.price >= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { - executeOrder/*66*/(order); - } - break; - case OrderTypes.StopSell: - if (order.pos === PositionTypes.Long && stock.price <= order.price) { - executeOrder/*66*/(order); - } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { - executeOrder/*66*/(order); - } - break; - default: - console.log("Invalid order type: " + order.type); - return; - } - } - } -} - -function setStockMarketContentCreated(b) { - stockMarketContentCreated = b; -} - -var stockMarketContentCreated = false; -var stockMarketPortfolioMode = false; -var COMM = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; -function displayStockMarketContent() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = false;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = false;} - - //Purchase WSE Account button - var wseAccountButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account"); - wseAccountButton.innerText = "Buy WSE Account - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, 2).toString(); - if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost)) { - wseAccountButton.setAttribute("class", "a-link-button"); - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount){ - wseAccountButton.innerText = "WSE Account - Purchased"; - wseAccountButton.setAttribute("class", "a-link-button-bought"); - } else { - wseAccountButton.setAttribute("class", "a-link-button-inactive"); - } - wseAccountButton.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = true; - initStockMarket(); - initSymbolToStockMap(); - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost); - displayStockMarketContent(); - return false; - }); - - //Purchase TIX API Access account - var tixApiAccessButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api"); - tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, 2).toString(); - if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost)) { - tixApiAccessButton.setAttribute("class", "a-link-button"); - } else if(_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess) { - tixApiAccessButton.innerText = "Trade Information eXchange (TIX) API Access - Purchased" - tixApiAccessButton.setAttribute("class", "a-link-button-bought"); - } else { - tixApiAccessButton.setAttribute("class", "a-link-button-inactive"); - } - tixApiAccessButton.addEventListener("click", function() { - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = true; - _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost); - displayStockMarketContent(); - return false; - }); - - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - - if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { - stockMarketContentCreated = false; - while (stockList.firstChild) { - stockList.removeChild(stockList.firstChild); - } - return; - } - - //Create stock market content if you have an account - if (!stockMarketContentCreated && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { - console.log("Creating Stock Market UI"); - document.getElementById("stock-market-commission").innerHTML = - "Commission Fees: Every transaction you make has a $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " commission fee.

" + - "WARNING: When you reset after installing Augmentations, the Stock Market is reset. " + - "This means all your positions are lost, so make sure to sell your stocks before installing " + - "Augmentations!"; - - var investopediaButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-investopedia"); - investopediaButton.addEventListener("click", function() { - var txt = "When making a transaction on the stock market, there are two " + - "types of positions: Long and Short. A Long position is the typical " + - "scenario where you buy a stock and earn a profit if the price of that " + - "stock increases. Meanwhile, a Short position is the exact opposite. " + - "In a Short position you purchase shares of a stock and earn a profit " + - "if the price of that stock decreases. This is also called 'shorting' a stock.

" + - "NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.

" + - "There are three different types of orders you can make to buy or sell " + - "stocks on the exchange: Market Order, Limit Order, and Stop Order. " + - "Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " + - "later on in the game.

" + - "When you place a Market Order to buy or sell a stock, the order executes " + - "immediately at whatever the current price of the stock is. For example " + - "if you choose to short a stock with 5000 shares using a Market Order, " + - "you immediately purchase those 5000 shares in a Short position at whatever " + - "the current market price is for that stock.

" + - "A Limit Order is an order that only executes under certain conditions. " + - "A Limit Order is used to buy or sell a stock at a specified price or better. " + - "For example, lets say you purchased a Long position of 100 shares of some stock " + - "at a price of $10 per share. You can place a Limit Order to sell those 100 shares " + - "at $50 or better. The Limit Order will execute when the price of the stock reaches a " + - "value of $50 or higher.

" + - "A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " + - "at a specified price (before the price gets 'worse'). For example, lets say you purchased " + - "a Short position of 100 shares of some stock at a price of $100 per share. " + - "The current price of the stock is $80 (a profit of $20 per share). You can place a " + - "Stop Order to sell the Short position if the stock's price reaches $90 or higher. " + - "This can be used to lock in your profits and limit any losses.

" + - "Here is a summary of how each order works and when they execute:

" + - "In a LONG Position:

" + - "A Limit Order to buy will execute if the stock's price <= order's price
" + - "A Limit Order to sell will execute if the stock's price >= order's price
" + - "A Stop Order to buy will execute if the stock's price >= order's price
" + - "A Stop Order to sell will execute if the stock's price <= order's price

" + - "In a SHORT Position:

" + - "A Limit Order to buy will execute if the stock's price >= order's price
" + - "A Limit Order to sell will execute if the stock's price <= order's price
" + - "A Stop Order to buy will execute if the stock's price <= order's price
" + - "A Stop Order to sell will execute if the stock's price >= order's price."; - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])(txt); - return false; - }); - - //Switch to Portfolio Mode Button - var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - - //Expand/Collapse tickers buttons - var expandBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-expand-tickers"), - collapseBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-collapse-tickers"), - stockList = document.getElementById("stock-market-list"); - if (expandBtn) { - expandBtn.addEventListener("click", ()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (!tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - if (collapseBtn) { - collapseBtn.addEventListener("click",()=>{ - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - for (var i = 0; i < tickerHdrs.length; ++i) { - if (tickerHdrs[i].classList.contains("active")) { - tickerHdrs[i].click(); - } - } - }); - } - - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); //Clicking headers opens/closes panels - stockMarketContentCreated = true; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - updateStockTicker(stock, null); - updateStockOrderList(stock); - } - } - } -} - -//Displays only stocks you have position/order in -function switchToPortfolioMode() { - stockMarketPortfolioMode = true; - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'All stocks' Mode" + - "Displays all stocks on the WSE"; - modeBtn.addEventListener("click", switchToDisplayAllMode); - } - while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} - - //Get Order book (create it if it hasn't been created) - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - var orders = {}; - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} - orders[stock.symbol] = []; - } - } - StockMarket["Orders"] = orders; - } - - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - var stockOrders = orderBook[stock.symbol]; - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - stockOrders.length === 0) {continue;} - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); -} - -//Displays all stocks -function switchToDisplayAllMode() { - stockMarketPortfolioMode = false; - var stockList = document.getElementById("stock-market-list"); - if (stockList == null) {return;} - var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); - if (modeBtn) { - modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + - "Displays only the stocks for which you have shares or orders"; - modeBtn.addEventListener("click", switchToPortfolioMode); - } - while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} - for (var name in StockMarket) { - if (StockMarket.hasOwnProperty(name)) { - var stock = StockMarket[name]; - if (!(stock instanceof Stock)) {continue;} //orders property is an array - createStockTicker(stock); - } - } - setStockTickerClickHandlers(); -} - -function createStockTicker(stock) { - if (!(stock instanceof Stock)) { - console.log("Invalid stock in createStockSticker()"); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - var li = document.createElement("li"), hdr = document.createElement("button"); - hdr.classList.add("accordion-header"); - hdr.setAttribute("id", tickerId + "-hdr"); - hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + stock.price; - - //Div for entire panel - var stockDiv = document.createElement("div"); - stockDiv.classList.add("accordion-panel"); - stockDiv.setAttribute("id", tickerId + "-panel"); - - /* Create panel DOM */ - var qtyInput = document.createElement("input"), - longShortSelect = document.createElement("select"), - orderTypeSelect = document.createElement("select"), - buyButton = document.createElement("span"), - sellButton = document.createElement("span"), - buyMaxButton = document.createElement("span"), - sellAllButton = document.createElement("span"), - positionTxt = document.createElement("p"), - orderList = document.createElement("ul"); - - qtyInput.classList.add("stock-market-input"); - qtyInput.placeholder = "Quantity (Shares)"; - qtyInput.setAttribute("id", tickerId + "-qty-input"); - qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " + - " || (4734 && event.keyCode<40) " + - " || (event.keyCode==46) )"); - - longShortSelect.classList.add("stock-market-input"); - longShortSelect.setAttribute("id", tickerId + "-pos-selector"); - var longOpt = document.createElement("option"); - longOpt.text = "Long"; - longShortSelect.add(longOpt); - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 2)) { - var shortOpt = document.createElement("option"); - shortOpt.text = "Short"; - longShortSelect.add(shortOpt); - } - - orderTypeSelect.classList.add("stock-market-input"); - orderTypeSelect.setAttribute("id", tickerId + "-order-selector"); - var marketOpt = document.createElement("option"); - marketOpt.text = "Market Order"; - orderTypeSelect.add(marketOpt); - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 3)) { - var limitOpt = document.createElement("option"); - limitOpt.text = "Limit Order"; - orderTypeSelect.add(limitOpt); - var stopOpt = document.createElement("option"); - stopOpt.text = "Stop Order"; - orderTypeSelect.add(stopOpt); - } - - buyButton.classList.add("stock-market-input"); - buyButton.classList.add("a-link-button"); - buyButton.innerHTML = "Buy"; - buyButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), - noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - placeOrder(stock, shares, price, type, pos); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - }); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellButton.classList.add("stock-market-input"); - sellButton.classList.add("a-link-button"); - sellButton.innerHTML = "Sell"; - sellButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var shares = Number(document.getElementById(tickerId + "-qty-input").value); - if (isNaN(shares)) {return false;} - switch (ordType) { - case "Market Order": - pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), - noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerText = "Place Sell " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitSell; - } else { - type = OrderTypes.StopSell; - } - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - placeOrder(stock, shares, price, type, pos); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - }); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - buyMaxButton.classList.add("stock-market-input"); - buyMaxButton.classList.add("a-link-button"); - buyMaxButton.innerHTML = "Buy MAX"; - buyMaxButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - var money = _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.toNumber(); - switch (ordType) { - case "Market Order": - var shares = Math.floor((money - COMM) / stock.price); - pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); - break; - case "Limit Order": - case "Stop Order": - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), - noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); - yesBtn.innerText = "Place Buy " + ordType; - noBtn.innerText = "Cancel Order"; - yesBtn.addEventListener("click", ()=>{ - var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; - if (ordType === "Limit Order") { - type = OrderTypes.LimitBuy; - } else { - type = OrderTypes.StopBuy; - } - var shares = Math.floor((money-COMM) / price); - placeOrder(stock, shares, price, type, pos); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); - }); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - sellAllButton.classList.add("stock-market-input"); - sellAllButton.classList.add("a-link-button"); - sellAllButton.innerHTML = "Sell ALL"; - sellAllButton.addEventListener("click", ()=>{ - var pos = longShortSelect.options[longShortSelect.selectedIndex].text; - pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; - var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; - switch (ordType) { - case "Market Order": - if (pos === PositionTypes.Long) { - var shares = stock.playerShares; - sellStock(stock, shares); - } else { - var shares = stock.playerShortShares; - sellShort(stock, shares, null); - } - break; - case "Limit Order": - case "Stop Order": - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: 'Sell All' only works for Market Orders") - break; - default: - console.log("ERROR: Invalid order type"); - break; - } - return false; - }); - - positionTxt.setAttribute("id", tickerId + "-position-text"); - positionTxt.classList.add("stock-market-position-text"); - stock.posTxtEl = positionTxt; - - orderList.setAttribute("id", tickerId + "-order-list"); - orderList.classList.add("stock-market-order-list"); - - stockDiv.appendChild(qtyInput); - stockDiv.appendChild(longShortSelect); - stockDiv.appendChild(orderTypeSelect); - stockDiv.appendChild(buyButton); - stockDiv.appendChild(sellButton); - stockDiv.appendChild(buyMaxButton); - stockDiv.appendChild(sellAllButton); - stockDiv.appendChild(positionTxt); - stockDiv.appendChild(orderList); - - li.appendChild(hdr); - li.appendChild(stockDiv); - document.getElementById("stock-market-list").appendChild(li); - - updateStockTicker(stock, true); - updateStockPlayerPosition(stock); - updateStockOrderList(stock); -} - -function setStockTickerClickHandlers() { - var stockList = document.getElementById("stock-market-list"); - var tickerHdrs = stockList.getElementsByClassName("accordion-header"); - if (tickerHdrs == null) { - console.log("ERROR: Could not find header elements for stock tickers"); - return; - } - for (var i = 0; i < tickerHdrs.length; ++i) { - tickerHdrs[i].onclick = function() { - this.classList.toggle("active"); - - var panel = this.nextElementSibling; - if (panel.style.display === "block") { - panel.style.display = "none"; - } else { - panel.style.display = "block"; - } - } - } -} - -//'increase' argument is a boolean indicating whether the price increased or decreased -function updateStockTicker(stock, increase) { - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} - if (!(stock instanceof Stock)) { - console.log("Invalid stock in updateStockTicker():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stock.playerShares > 0 || stock.playerShortShares > 0) { - updateStockPlayerPosition(stock); - } - - var hdr = document.getElementById(tickerId + "-hdr"); - - if (hdr == null) { - if (!stockMarketPortfolioMode) {console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol);} - return; - } - hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2); - if (increase != null) { - increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red"; - } -} - -function updateStockPlayerPosition(stock) { - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} - if (!(stock instanceof Stock)) { - console.log("Invalid stock in updateStockPlayerPosition():"); - console.log(stock); - return; - } - var tickerId = "stock-market-ticker-" + stock.symbol; - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr"); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - if (!(stock.posTxtEl instanceof Element)) { - stock.posTxtEl = document.getElementById(tickerId + "-position-text"); - } - if (stock.posTxtEl == null) { - console.log("ERROR: Could not find stock position element for: " + stock.symbol); - return; - } - - //Calculate returns - var totalCost = stock.playerShares * stock.playerAvgPx, - gains = (stock.price - stock.playerAvgPx) * stock.playerShares, - percentageGains = gains / totalCost; - if (isNaN(percentageGains)) {percentageGains = 0;} - - var shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx, - shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares, - shortPercentageGains = shortGains/ shortTotalCost; - if (isNaN(shortPercentageGains)) {shortPercentageGains = 0;} - - stock.posTxtEl.innerHTML = - "

Long Position: " + - "Shares in the long position will increase " + - "in value if the price of the corresponding stock increases

" + - "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShares, 0) + - "
Average Price: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgPx).format('$0.000a') + - " (Total Cost: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(totalCost).format('$0.000a') + ")" + - "
Profit: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(gains).format('$0.000a') + - " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(percentageGains*100, 2) + "%)

"; - if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 2)) { - stock.posTxtEl.innerHTML += - "

Short Position: " + - "Shares in short position will increase " + - "in value if the price of the corresponding stock decreases

" + - "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShortShares, 0) + - "
Average Price: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgShortPx).format('$0.000a') + - " (Total Cost: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(shortTotalCost).format('$0.000a') + ")" + - "
Profit: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(shortGains).format('$0.000a') + - " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shortPercentageGains*100, 2) + "%)" + - "

Orders:

"; - } - -} - -function updateStockOrderList(stock) { - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} - var tickerId = "stock-market-ticker-" + stock.symbol; - var orderList = document.getElementById(tickerId + "-order-list"); - if (orderList == null) { - if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);} - return; - } - - var orderBook = StockMarket["Orders"]; - if (orderBook == null) { - console.log("ERROR: Could not find order book in stock market"); - return; - } - var stockOrders = orderBook[stock.symbol]; - if (stockOrders == null) { - console.log("ERROR: Could not find orders for: " + stock.symbol); - return; - } - - if (stockMarketPortfolioMode) { - if (stock.playerShares === 0 && stock.playerShortShares === 0 && - StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && - StockMarket["Orders"][stock.symbol].length === 0) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr"); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel"); - return; - } else { - //If the ticker hasn't been created, create it (handles updating) - //If it has been created, continue normally - if (document.getElementById(tickerId + "-hdr") == null) { - createStockTicker(stock); - setStockTickerClickHandlers(); - return; - } - } - } - - //Remove everything from list - while (orderList.firstChild) { - orderList.removeChild(orderList.firstChild); - } - - for (var i = 0; i < stockOrders.length; ++i) { - (function() { - var order = stockOrders[i]; - var li = document.createElement("li"); - li.style.padding = "4px"; - var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); - li.style.color = "white"; - li.innerText = order.type + " - " + posText + " - " + - order.shares + " @ $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(order.price, 2); - - var cancelButton = document.createElement("span"); - cancelButton.classList.add("stock-market-order-cancel-btn"); - cancelButton.classList.add("a-link-button"); - cancelButton.innerHTML = "Cancel Order"; - cancelButton.addEventListener("click", function() { - cancelOrder({order: order}, null); - return false; - }); - li.appendChild(cancelButton); - orderList.appendChild(li); - }()); - - } -} - - - - -/***/ }), -/* 23 */ +/* 19 */ /*!*************************!*\ !*** ./src/Settings.js ***! \*************************/ @@ -19633,7 +16232,7 @@ function setSettingsLabels() { /***/ }), -/* 24 */ +/* 20 */ /*!************************************************!*\ !*** ./node_modules/decimal.js/decimal.es6.js ***! \************************************************/ @@ -24426,7 +21025,7 @@ PI = new Decimal(pi); /***/ }), -/* 25 */ +/* 21 */ /*!************************************!*\ !*** ./src/InteractiveTutorial.js ***! \************************************/ @@ -24442,7 +21041,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "iTutorialIsRunning", function() { return iTutorialIsRunning; }); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.js */ 5); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); @@ -25110,7 +21709,647 @@ function iTutorialSetText(txt) { /***/ }), -/* 26 */ +/* 22 */ +/*!********************************!*\ + !*** ./src/NetscriptWorker.js ***! + \********************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorkerScript", function() { return WorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "workerScripts", function() { return workerScripts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPorts", function() { return NetscriptPorts; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptsLoop", function() { return runScriptsLoop; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killWorkerScript", function() { return killWorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addWorkerScript", function() { return addWorkerScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateOnlineScriptTimes", function() { return updateOnlineScriptTimes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeWorkerScripts", function() { return prestigeWorkerScripts; }); +/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 80); +/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31); +/* harmony import */ var _NetscriptJSEvaluator_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptJSEvaluator.js */ 60); +/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptPort.js */ 65); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/acorn.js */ 32); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); + + + + + + + + + + + + + + +function WorkerScript(runningScriptObj) { + this.name = runningScriptObj.filename; + this.running = false; + this.serverIp = null; + this.code = runningScriptObj.scriptRef.code; + this.env = new _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__["Environment"](this); + this.env.set("args", runningScriptObj.args.slice()); + this.output = ""; + this.ramUsage = 0; + this.scriptRef = runningScriptObj; + this.errorMessage = ""; + this.args = runningScriptObj.args.slice(); + this.delay = null; + this.fnWorker = null; //Workerscript for a function call + this.checkingRam = false; + this.loadedFns = {}; //Stores names of fns that are "loaded" by this script, thus using RAM. Used for static RAM evaluation + this.disableLogs = {}; //Stores names of fns that should have logs disabled + + //Properties used for dynamic RAM evaluation + this.dynamicRamUsage = 1.4; + this.dynamicLoadedFns = {}; +} + +//Returns the server on which the workerScript is running +WorkerScript.prototype.getServer = function() { + return _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][this.serverIp]; +} + +//Returns the Script object for the underlying script +WorkerScript.prototype.getScript = function() { + let server = this.getServer(); + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename === this.name) { + return server.scripts[i]; + } + } + console.log("ERROR: Failed to find underlying Script object in WorkerScript.getScript(). This probably means somethings wrong"); + return null; +} + +//Array containing all scripts that are running across all servers, to easily run them all +let workerScripts = []; + +var NetscriptPorts = []; +for (var i = 0; i < _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NumNetscriptPorts; ++i) { + NetscriptPorts.push(new _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_6__["NetscriptPort"]()); +} + +function prestigeWorkerScripts() { + for (var i = 0; i < workerScripts.length; ++i) { + Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); + workerScripts[i].env.stopFlag = true; + } + Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])(5000); //Force UI to update + workerScripts.length = 0; +} + +// JS script promises need a little massaging to have the same guarantees as netscript +// promises. This does said massaging and kicks the script off. It returns a promise +// that resolves or rejects when the corresponding worker script is done. +function startJsScript(workerScript) { + workerScript.running = true; + + // The name of the currently running netscript function, to prevent concurrent + // calls to hack, grow, etc. + let runningFn = null; + + // We need to go through the environment and wrap each function in such a way that it + // can be called at most once at a time. This will prevent situations where multiple + // hack promises are outstanding, for example. + function wrap(propName, f) { + // This function unfortunately cannot be an async function, because we don't + // know if the original one was, and there's no way to tell. + return function (...args) { + // Wrap every netscript function with a check for the stop flag. + // This prevents cases where we never stop because we are only calling + // netscript functions that don't check this. + // This is not a problem for legacy Netscript because it also checks the + // stop flag in the evaluator. + if (workerScript.env.stopFlag) {throw workerScript;} + + if (propName === "sleep") return f(...args); // OK for multiple simultaneous calls to sleep. + + const msg = "Concurrent calls to Netscript functions not allowed! " + + "Did you forget to await hack(), grow(), or some other " + + "promise-returning function? (Currently running: %s tried to run: %s)" + if (runningFn) { + workerScript.errorMessage = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])(workerScript, sprintf(msg, runningFn, propName), null) + throw workerScript; + } + runningFn = propName; + let result = f(...args); + if (result && result.finally !== undefined) { + return result.finally(function () { + runningFn = null; + }); + } else { + runningFn = null; + return result; + } + } + }; + + for (let prop in workerScript.env.vars) { + if (typeof workerScript.env.vars[prop] !== "function") continue; + workerScript.env.vars[prop] = wrap(prop, workerScript.env.vars[prop]); + } + + // Note: the environment that we pass to the JS script only needs to contain the functions visible + // to that script, which env.vars does at this point. + return Object(_NetscriptJSEvaluator_js__WEBPACK_IMPORTED_MODULE_5__["executeJSScript"])(workerScript.getServer().scripts, + workerScript).then(function (mainReturnValue) { + if (mainReturnValue === undefined) return workerScript; + return [mainReturnValue, workerScript]; + }).catch(e => { + if (e instanceof Error) { + workerScript.errorMessage = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["makeRuntimeRejectMsg"])( + workerScript, e.message + (e.stack && ("\nstack:\n" + e.stack.toString()) || "")); + throw workerScript; + } else if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(e)) { + workerScript.errorMessage = e; + throw workerScript; + } + throw e; // Don't know what to do with it, let's rethrow. + }); +} + +//Loop through workerScripts and run every script that is not currently running +function runScriptsLoop() { + var scriptDeleted = false; + + //Delete any scripts that finished or have been killed. Loop backwards bc removing items screws up indexing + for (var i = workerScripts.length - 1; i >= 0; i--) { + if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) { + scriptDeleted = true; + //Delete script from the runningScripts array on its host serverIp + var ip = workerScripts[i].serverIp; + var name = workerScripts[i].name; + + //Free RAM + _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].ramUsed -= workerScripts[i].ramUsage; + + //Delete script from Active Scripts + Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["deleteActiveScriptsItem"])(workerScripts[i]); + + for (var j = 0; j < _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.length; j++) { + if (_Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].filename == name && + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(_Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts[j].args, workerScripts[i].args)) { + _Server_js__WEBPACK_IMPORTED_MODULE_7__["AllServers"][ip].runningScripts.splice(j, 1); + break; + } + } + + //Delete script from workerScripts + workerScripts.splice(i, 1); + } + } + if (scriptDeleted) {Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])();} //Force Update + + + //Run any scripts that haven't been started + for (var i = 0; i < workerScripts.length; i++) { + //If it isn't running, start the script + if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { + let p = null; // p is the script's result promise. + if (workerScripts[i].name.endsWith(".js") || workerScripts[i].name.endsWith(".ns")) { + p = startJsScript(workerScripts[i]); + } else { + try { + var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_9__["parse"])(workerScripts[i].code, {sourceType:"module"}); + //console.log(ast); + } catch (e) { + console.log("Error parsing script: " + workerScripts[i].name); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Syntax ERROR in " + workerScripts[i].name + ":
" + e); + workerScripts[i].env.stopFlag = true; + continue; + } + workerScripts[i].running = true; + p = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["evaluate"])(ast, workerScripts[i]); + } + + //Once the code finishes (either resolved or rejected, doesnt matter), set its + //running status to false + p.then(function(w) { + console.log("Stopping script " + w.name + " because it finished running naturally"); + w.running = false; + w.env.stopFlag = true; + w.scriptRef.log("Script finished running"); + }).catch(function(w) { + if (w instanceof Error) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); + console.log("ERROR: Evaluating workerscript returns an Error. THIS SHOULDN'T HAPPEN: " + w.toString()); + return; + } else if (w.constructor === Array && w.length === 2 && w[0] === "RETURNSTATEMENT") { + //Script ends with a return statement + console.log("Script returning with value: " + w[1]); + //TODO maybe do something with this in the future + return; + } else if (w instanceof WorkerScript) { + if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w.errorMessage)) { + var errorTextArray = w.errorMessage.split("|"); + if (errorTextArray.length != 4) { + console.log("ERROR: Something wrong with Error text in evaluator..."); + console.log("Error text: " + errorText); + return; + } + var serverIp = errorTextArray[1]; + var scriptName = errorTextArray[2]; + var errorMsg = errorTextArray[3]; + + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime error:
Server Ip: " + serverIp + + "
Script name: " + scriptName + + "
Args:" + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["printArray"])(w.args) + "
" + errorMsg); + w.scriptRef.log("Script crashed with runtime error"); + } else { + w.scriptRef.log("Script killed"); + } + w.running = false; + w.env.stopFlag = true; + + } else if (Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["isScriptErrorMessage"])(w)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Script runtime unknown error. This is a bug please contact game developer"); + console.log("ERROR: Evaluating workerscript returns only error message rather than WorkerScript object. THIS SHOULDN'T HAPPEN: " + w.toString()); + return; + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("An unknown script died for an unknown reason. This is a bug please contact game dev"); + console.log(w); + } + }); + } + } + + setTimeout(runScriptsLoop, 6000); +} + +//Queues a script to be killed by settings its stop flag to true. Then, the code will reject +//all of its promises recursively, and when it does so it will no longer be running. +//The runScriptsLoop() will then delete the script from worker scripts +function killWorkerScript(runningScriptObj, serverIp) { + for (var i = 0; i < workerScripts.length; i++) { + if (workerScripts[i].name == runningScriptObj.filename && workerScripts[i].serverIp == serverIp && + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["compareArrays"])(workerScripts[i].args, runningScriptObj.args)) { + workerScripts[i].env.stopFlag = true; + Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(workerScripts[i]); + //Recursively kill all functions + var curr = workerScripts[i]; + while (curr.fnWorker) { + curr.fnWorker.env.stopFlag = true; + Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["killNetscriptDelay"])(curr.fnWorker); + curr = curr.fnWorker; + } + return true; + } + } + return false; +} + +//Queues a script to be run +function addWorkerScript(runningScriptObj, server) { + var filename = runningScriptObj.filename; + + //Update server's ram usage + var threads = 1; + if (runningScriptObj.threads && !isNaN(runningScriptObj.threads)) { + threads = runningScriptObj.threads; + } else { + runningScriptObj.threads = 1; + } + var ramUsage = runningScriptObj.scriptRef.ramUsage * threads + * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, threads-1); + var ramAvailable = server.maxRam - server.ramUsed; + if (ramUsage > ramAvailable) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_10__["dialogBoxCreate"])("Not enough RAM to run script " + runningScriptObj.filename + " with args " + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["printArray"])(runningScriptObj.args) + ". This likely occurred because you re-loaded " + + "the game and the script's RAM usage increased (either because of an update to the game or " + + "your changes to the script.)"); + return; + } + server.ramUsed += ramUsage; + + //Create the WorkerScript + var s = new WorkerScript(runningScriptObj); + s.serverIp = server.ip; + s.ramUsage = ramUsage; + + //Add the WorkerScript to the Active Scripts list + Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["addActiveScriptsItem"])(s); + + //Add the WorkerScript + workerScripts.push(s); + return; +} + +//Updates the online running time stat of all running scripts +function updateOnlineScriptTimes(numCycles = 1) { + var time = (numCycles * _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed) / 1000; //seconds + for (var i = 0; i < workerScripts.length; ++i) { + workerScripts[i].scriptRef.onlineRunningTime += time; + } +} + + + + +/***/ }), +/* 23 */ +/*!***********************!*\ + !*** ./src/Crimes.js ***! + \***********************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "determineCrimeSuccess", function() { return determineCrimeSuccess; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findCrime", function() { return findCrime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Crimes", function() { return Crimes; }); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); + + + + + +function Crime(name, type, time, money, difficulty, karma, params) { + this.name = name; + this.type = type; + this.time = time; + this.money = money; + this.difficulty = difficulty; + this.karma = karma; + + this.hacking_success_weight = params.hacking_success_weight ? params.hacking_success_weight : 0; + this.strength_success_weight = params.strength_success_weight ? params.strength_success_weight : 0; + this.defense_success_weight = params.defense_success_weight ? params.defense_success_weight : 0; + this.dexterity_success_weight = params.dexterity_success_weight ? params.dexterity_success_weight : 0; + this.agility_success_weight = params.agility_success_weight ? params.agility_success_weight : 0; + this.charisma_success_weight = params.charisma_success_weight ? params.charisma_success_weight : 0; + + this.hacking_exp = params.hacking_exp ? params.hacking_exp : 0; + this.strength_exp = params.strength_exp ? params.strength_exp : 0; + this.defense_exp = params.defense_exp ? params.defense_exp : 0; + this.dexterity_exp = params.dexterity_exp ? params.dexterity_exp : 0; + this.agility_exp = params.agility_exp ? params.agility_exp : 0; + this.charisma_exp = params.charisma_exp ? params.charisma_exp : 0; + this.intelligence_exp = params.intelligence_exp ? params.intelligence_exp : 0; + + this.kills = params.kills ? params.kills : 0; +} + +Crime.prototype.commit = function(div=1, singParams=null) { + if (div <= 0) {div = 1;} + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crimeType = this.type; + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].startCrime( + this.hacking_exp/div, + this.strength_exp/div, + this.defense_exp/div, + this.dexterity_exp/div, + this.agility_exp/div, + this.charisma_exp/div, + this.money/div, this.time, singParams); + return this.time; +} + +Crime.prototype.successRate = function() { + var chance = (this.hacking_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].hacking_skill + + this.strength_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].strength + + this.defense_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].defense + + this.dexterity_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].dexterity + + this.agility_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].agility + + this.charisma_success_weight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].charisma + + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeWeight * _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].intelligence); + chance /= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].MaxSkillLevel; + chance /= this.difficulty; + chance *= _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].crime_success_mult; + return Math.min(chance, 1); +} + +const Crimes = { + Shoplift: new Crime("Shoplift", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeShoplift, 2e3, 15e3, 1/20, 0.1, { + dexterity_success_weight: 1, + agility_success_weight: 1, + + dexterity_exp: 2, + agility_exp: 2, + }), + + RobStore: new Crime("Rob Store", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeRobStore, 60e3, 400e3, 1/5, 0.5, { + hacking_exp: 30, + dexterity_exp: 45, + agility_exp: 45, + + hacking_success_weight: 0.5 , + dexterity_success_weight: 2, + agility_success_weight: 1, + + intelligence_exp: 0.25 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), + + Mug: new Crime("Mug", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeMug, 4e3, 36e3, 1/5, 0.25, { + strength_exp: 3, + defense_exp: 3, + dexterity_exp: 3, + agility_exp: 3, + + strength_success_weight: 1.5, + defense_success_weight: 0.5, + dexterity_success_weight: 1.5, + agility_success_weight: 0.5, + }), + + Larceny: new Crime("Larceny", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeLarceny, 90e3, 800e3, 1/3, 1.5, { + hacking_exp: 45, + dexterity_exp: 60, + agility_exp: 60, + + hacking_skill_success_weight: 0.5, + dexterity_success_weight: 1, + agility_success_weight: 1, + + intelligence_exp: 0.5 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), + + DealDrugs: new Crime("Deal Drugs", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeDrugs, 10e3, 120e3, 1, 0.5, { + dexterity_exp: 5, + agility_exp: 5, + charisma_exp: 10, + + charisma_success_weight: 3, + dexterity_success_weight: 2, + agility_success_weight: 1, + }), + + BondForgery: new Crime("Bond Forgery", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeBondForgery, 300e3, 4.5e6, 1/2, 0.1, { + hacking_exp: 100, + dexterity_exp: 150, + charisma_exp: 15, + + hacking_skill_success_weight: 0.05, + dexterity_success_weight: 1.25, + + intelligence_exp: 2 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), + + TraffickArms: new Crime("Traffick Arms", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeTraffickArms, 40e3, 600e3, 2, 1, { + strength_exp: 20, + defense_exp: 20, + dexterity_exp: 20, + agility_exp: 20, + charisma_exp: 40, + + charisma_success_weight: 1, + strength_success_weight: 1, + defense_success_weight: 1, + dexterity_success_weight: 1, + agility_success_weight: 1, + }), + + Homicide: new Crime("Homicide", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHomicide, 3e3, 45e3, 1, 3, { + strength_exp: 2, + defense_exp: 2, + dexterity_exp: 2, + agility_exp: 2, + + strength_success_weight: 2, + defense_success_weight: 2, + dexterity_success_weight: 0.5, + agility_success_weight: 0.5, + + kills: 1, + }), + + GrandTheftAuto: new Crime("Grand Theft Auto", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeGrandTheftAuto, 80e3, 1.6e6, 8, 5, { + strength_exp: 20, + defense_exp: 20, + dexterity_exp: 20, + agility_exp: 80, + charisma_exp: 40, + + hacking_skill_success_weight: 1, + strength_success_weight: 1, + dexterity_success_weight: 4, + agility_success_weight: 2, + charisma_success_weight: 2, + + intelligence_exp: _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), + + Kidnap: new Crime("Kidnap", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeKidnap, 120e3, 3.6e6, 5, 6, { + strength_exp: 80, + defense_exp: 80, + dexterity_exp: 80, + agility_exp: 80, + charisma_exp: 80, + + charisma_success_weight: 1, + strength_success_weight: 1, + dexterity_success_weight: 1, + agility_success_weight: 1, + + intelligence_exp: 2 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), + + Assassination: new Crime("Assassination", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeAssassination, 300e3, 12e6, 8, 10, { + strength_exp: 300, + defense_exp: 300, + dexterity_exp: 300, + agility_exp: 300, + + strength_success_weight: 1, + dexterity_success_weight: 2, + agility_success_weight: 1, + + intelligence_exp: 5 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + + kills: 1, + }), + + Heist: new Crime("Heist", _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].CrimeHeist, 600e3, 120e6, 18, 15, { + hacking_exp: 450, + strength_exp: 450, + defense_exp: 450, + dexterity_exp: 450, + agility_exp: 450, + charisma_exp: 450, + + hacking_skill_success_weight: 1, + strength_success_weight: 1, + defense_success_weight: 1, + dexterity_success_weight: 1, + agility_success_weight: 1, + charisma_success_weight: 1, + + intelligence_exp: 10 * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceCrimeBaseExpGain, + }), +}; + +function determineCrimeSuccess(type, moneyGained) { + var chance = 0; + var found = false; + for(const i in Crimes) { + const crime = Crimes[i]; + if(crime.type == type) { + chance = crime.successRate(); + found = true; + break; + } + } + if(!found) { + console.log(crime); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("ERR: Unrecognized crime type. This is probably a bug please contact the developer"); + return; + } + + if (Math.random() <= chance) { + //Success + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].gainMoney(moneyGained); + return true; + } else { + //Failure + return false; + } +} + +function findCrime(roughName) { + if (roughName.includes("shoplift")) { + return Crimes.Shoplift; + } else if (roughName.includes("rob") && roughName.includes("store")) { + return Crimes.RobStore; + } else if (roughName.includes("mug")) { + return Crimes.Mug; + } else if (roughName.includes("larceny")) { + return Crimes.Larceny; + } else if (roughName.includes("drugs")) { + return Crimes.DealDrugs; + } else if (roughName.includes("bond") && roughName.includes("forge")) { + return Crimes.BondForgery; + } else if (roughName.includes("traffick") && roughName.includes("arms")) { + return Crimes.TraffickArms; + } else if (roughName.includes("homicide")) { + return Crimes.Homicide; + } else if (roughName.includes("grand") && roughName.includes("auto")) { + return Crimes.GrandTheftAuto; + } else if (roughName.includes("kidnap")) { + return Crimes.Kidnap; + } else if (roughName.includes("assassinate")) { + return Crimes.Assassination; + } else if (roughName.includes("heist")) { + return Crimes.Heist; + } + return null; +} + + + + +/***/ }), +/* 24 */ /*!***********************!*\ !*** ./src/Script.js ***! \***********************/ @@ -25128,20 +22367,20 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScriptFilename", function() { return isScriptFilename; }); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Fconf.js */ 33); -/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25); -/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 6); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); +/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Fconf.js */ 30); +/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 21); +/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile.js */ 43); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn.js */ 36); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile.js */ 58); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/acorn.js */ 32); /* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); var ace = __webpack_require__(/*! brace */ 196); @@ -26108,3790 +23347,3589 @@ _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.AllS -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) + +/***/ }), +/* 25 */ +/*!**********************!*\ + !*** ./src/Alias.js ***! + \**********************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Aliases", function() { return Aliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalAliases", function() { return GlobalAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printAliases", function() { return printAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseAliasDeclaration", function() { return parseAliasDeclaration; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeAlias", function() { return removeAlias; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "substituteAliases", function() { return substituteAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAliases", function() { return loadAliases; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGlobalAliases", function() { return loadGlobalAliases; }); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Terminal.js */ 15); + + +let Aliases = {}; +let GlobalAliases = {}; + +function loadAliases(saveString) { + if (saveString === "") { + Aliases = {}; + } else { + Aliases = JSON.parse(saveString); + } +} + +function loadGlobalAliases(saveString) { + if (saveString === "") { + GlobalAliases = {}; + } else { + GlobalAliases = JSON.parse(saveString); + } +} + +//Print all aliases to terminal +function printAliases() { + for (var name in Aliases) { + if (Aliases.hasOwnProperty(name)) { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]); + } + } + for (var name in GlobalAliases) { + if (GlobalAliases.hasOwnProperty(name)) { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_0__["post"])("global alias " + name + "=" + GlobalAliases[name]); + } + } +} + +//True if successful, false otherwise +function parseAliasDeclaration(dec,global=false) { + var re = /^([_|\w|!|%|,|@]+)="(.+)"$/; + var matches = dec.match(re); + if (matches == null || matches.length != 3) {return false;} + if (global){ + addGlobalAlias(matches[1],matches[2]); + } else { + addAlias(matches[1], matches[2]); + } + return true; +} + +function addAlias(name, value) { + if (name in GlobalAliases){ + delete GlobalAliases[name]; + } + Aliases[name] = value; +} + +function addGlobalAlias(name, value) { + if (name in Aliases){ + delete Aliases[name]; + } + GlobalAliases[name] = value; +} + +function getAlias(name) { + if (Aliases.hasOwnProperty(name)) { + return Aliases[name]; + } + return null; +} + +function getGlobalAlias(name) { + if (GlobalAliases.hasOwnProperty(name)) { + return GlobalAliases[name]; + } + return null; +} + +function removeAlias(name) { + if (Aliases.hasOwnProperty(name)) { + delete Aliases[name]; + return true; + } + if (GlobalAliases.hasOwnProperty(name)) { + delete GlobalAliases[name]; + return true; + } + return false; +} + +//Returns the original string with any aliases substituted in +//Aliases only applied to "whole words", one level deep +function substituteAliases(origCommand) { + var commandArray = origCommand.split(" "); + if (commandArray.length>0){ + var alias = getAlias(commandArray[0]); + if (alias != null) { + commandArray[0] = alias; + } else { + var alias = getGlobalAlias(commandArray[0]); + if (alias != null) { + commandArray[0] = alias; + } + } + for (var i = 0; i < commandArray.length; ++i) { + var alias = getGlobalAlias(commandArray[i]); + if (alias != null) { + commandArray[i] = alias; + } + } + } + return commandArray.join(" "); +} + + + + +/***/ }), +/* 26 */ +/*!***********************************!*\ + !*** ./src/NetscriptFunctions.js ***! + \***********************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptFunctions", function() { return NetscriptFunctions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSingularitySFFlags", function() { return initSingularitySFFlags; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasSingularitySF", function() { return hasSingularitySF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBn11SF", function() { return hasBn11SF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasWallStreetSF", function() { return hasWallStreetSF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wallStreetSFLvl", function() { return wallStreetSFLvl; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCorporationSF", function() { return hasCorporationSF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAISF", function() { return hasAISF; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBladeburnerSF", function() { return hasBladeburnerSF; }); +/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Crimes.js */ 23); +/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Bladeburner.js */ 40); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company.js */ 8); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./DarkWeb.js */ 82); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./HacknetNode.js */ 38); +/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Location.js */ 4); +/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Message.js */ 27); +/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Missions.js */ 39); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./StockMarket.js */ 29); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./TextFile.js */ 58); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); +/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31); +/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 80); +/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./NetscriptPort.js */ 65); +/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! decimal.js */ 20); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); +var sprintf = __webpack_require__(/*! sprintf-js */ 114).sprintf, + vsprintf = __webpack_require__(/*! sprintf-js */ 114).vsprintf + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +var hasCorporationSF = false, //Source-File 3 + hasSingularitySF = false, //Source-File 4 + hasAISF = false, //Source-File 5 + hasBladeburnerSF = false, //Source-File 6 + hasBladeburner2079SF = false, //Source-File 7 + hasWallStreetSF = false, //Source-File 8 + hasBn11SF = false; //Source-File 11 + +var singularitySFLvl=1, wallStreetSFLvl=1; + +var possibleLogs = { + ALL: true, + scan: true, + hack: true, + sleep: true, + disableLog: true, + enableLog: true, + grow: true, + weaken: true, + nuke: true, + brutessh: true, + ftpcrack: true, + relaysmtp: true, + httpworm: true, + sqlinject: true, + spawn: true, + kill: true, + killall: true, + scp: true, + getHackingLevel: true, + getServerMoneyAvailable: true, + getServerSecurityLevel: true, + getServerBaseSecurityLevel: true, + getServerMinSecurityLevel: true, + getServerRequiredHackingLevel: true, + getServerMaxMoney: true, + getServerGrowth: true, + getServerNumPortsRequired: true, + getServerRam: true, + buyStock: true, + sellStock: true, + purchaseServer: true, + deleteServer: true, + universityCourse: true, + gymWorkout: true, + travelToCity: true, + purchaseTor: true, + purchaseProgram: true, + stopAction: true, + upgradeHomeRam: true, + workForCompany: true, + applyToCompany: true, + joinFaction: true, + workForFaction: true, + createProgram: true, + commitCrime: true, + shortStock: true, + sellShort: true, +} + +//Used to check and set flags for every Source File, despite the name of the function +function initSingularitySFFlags() { + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles.length; ++i) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 3) {hasCorporationSF = true;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 4) { + hasSingularitySF = true; + singularitySFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].lvl; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 5) {hasAISF = true;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 8) { + hasWallStreetSF = true; + wallStreetSFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].lvl; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 11) {hasBn11SF = true;} + } +} + +function NetscriptFunctions(workerScript) { + var updateDynamicRam = function(fnName, ramCost) { + if (workerScript.dynamicLoadedFns[fnName]) {return;} + workerScript.dynamicLoadedFns[fnName] = true; + workerScript.dynamicRamUsage += ramCost; + if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, + "Dynamic RAM usage calculated to be greater than initial RAM usage. " + + "This is probably because you somehow circumvented the static RAM " + + "calculation.

Please don't do that :("); + } + }; + + var updateStaticRam = function(fnName, ramCost) { + if (workerScript.loadedFns[fnName]) { + return 0; + } else { + workerScript.loadedFns[fnName] = true; + return ramCost; + } + }; + + return { + Math : Math, + Date : Date, + Number : Number, + hacknetnodes : _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknetNodeWrappers, + sprintf : sprintf, + vsprintf: vsprintf, + scan : function(ip=workerScript.serverIp, hostnames=true){ + if (workerScript.checkingRam) { + return updateStaticRam("scan", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); + } + updateDynamicRam("scan", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, 'Invalid IP or hostname passed into scan() command'); + } + var out = []; + for (var i = 0; i < server.serversOnNetwork.length; i++) { + var entry; + if (hostnames) { + entry = server.getServerOnNetwork(i).hostname; + } else { + entry = server.getServerOnNetwork(i).ip; + } + if (entry == null) { + continue; + } + out.push(entry); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) { + workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname); + } + return out; + }, + hack : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("hack", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHackRamCost); + } + updateDynamicRam("hack", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHackRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument"); + } + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); + } + + //Calculate the hacking time + var hackingTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingTime"])(server); //This is in seconds + + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access"); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access"); + } + + if (server.requiredHackingSkill > _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill) { + workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); + } + + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { + workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")"); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(hackingTime* 1000, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + var hackChance = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingChance"])(server); + var rand = Math.random(); + var expGainedOnSuccess = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; + var expGainedOnFailure = (expGainedOnSuccess / 4); + if (rand < hackChance) { //Success! + var moneyGained = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculatePercentMoneyHacked"])(server); + moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads; + + //Over-the-top safety checks + if (moneyGained <= 0) { + moneyGained = 0; + expGainedOnSuccess = expGainedOnFailure; + } + if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;} + server.moneyAvailable -= moneyGained; + if (server.moneyAvailable < 0) {server.moneyAvailable = 0;} + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainMoney(moneyGained); + workerScript.scriptRef.onlineMoneyMade += moneyGained; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug += moneyGained; + workerScript.scriptRef.recordHack(server.ip, moneyGained, threads); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGainedOnSuccess); + workerScript.scriptRef.onlineExpGained += expGainedOnSuccess; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { + workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); + } + server.fortify(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerFortifyAmount * threads); + return Promise.resolve(moneyGained); + } else { + //Player only gains 25% exp for failure? + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGainedOnFailure); + workerScript.scriptRef.onlineExpGained += expGainedOnFailure; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { + workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGainedOnFailure, 4) + " exp (t=" + threads + ")"); + } + return Promise.resolve(0); + } + }); + }, + sleep : function(time){ + if (workerScript.checkingRam) {return 0;} + if (time === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument"); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) { + workerScript.scriptRef.log("Sleeping for " + time + " milliseconds"); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(time, workerScript).then(function() { + return Promise.resolve(true); + }); + }, + grow : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("grow", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGrowRamCost); + } + updateDynamicRam("grow", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGrowRamCost); + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip); + } + + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access"); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access"); + } + + var growTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateGrowTime"])(server); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { + workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(growTime/1000, 3) + " seconds (t=" + threads + ")"); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(growTime, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + server.moneyAvailable += (1 * threads); //It can be grown even if it has no money + var growthPercentage = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["processSingleServerGrowth"])(server, 450 * threads); + workerScript.scriptRef.recordGrow(server.ip, threads); + var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; + if (growthPercentage == 1) { + expGain = 0; + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { + workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(growthPercentage*100 - 100, 6) + "%. Gained " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")"); + } + workerScript.scriptRef.onlineExpGained += expGain; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGain); + return Promise.resolve(growthPercentage); + }); + }, + weaken : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("weaken", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptWeakenRamCost); + } + updateDynamicRam("weaken", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptWeakenRamCost); + var threads = workerScript.scriptRef.threads; + if (isNaN(threads) || threads < 1) {threads = 1;} + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip); + } + + //No root access or skill level too low + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access"); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access"); + } + + var weakenTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateWeakenTime"])(server); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { + workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(weakenTime/1000, 3) + " seconds (t=" + threads + ")"); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(weakenTime, workerScript).then(function() { + if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} + server.weaken(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerWeakenAmount * threads); + workerScript.scriptRef.recordWeaken(server.ip, threads); + var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { + workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty + + ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")"); + } + workerScript.scriptRef.onlineExpGained += expGain; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGain); + return Promise.resolve(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerWeakenAmount * threads); + }); + }, + print : function(args){ + if (workerScript.checkingRam) {return 0;} + if (args === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument"); + } + workerScript.scriptRef.log(args.toString()); + }, + tprint : function(args) { + if (workerScript.checkingRam) {return 0;} + if (args === undefined || args == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument"); + } + var x = args.toString(); + if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isHTML"])(x)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].takeDamage(1); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_28__["dialogBoxCreate"])("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims:

" + + "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!

" + + "(You lost 1 HP)"); + return; + } + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_21__["post"])(workerScript.scriptRef.filename + ": " + args.toString()); + }, + clearLog : function() { + if (workerScript.checkingRam) {return 0;} + workerScript.scriptRef.clearLog(); + }, + disableLog : function(fn) { + if (workerScript.checkingRam) {return 0;} + if(possibleLogs[fn]===undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to disableLog: "+fn); + } + workerScript.disableLogs[fn] = true; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) { + workerScript.scriptRef.log("Disabled logging for " + fn); + } + }, + enableLog : function(fn) { + if (workerScript.checkingRam) {return 0;} + if(possibleLogs[fn]===undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to enableLog: "+fn); + } + delete workerScript.disableLogs[fn]; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) { + workerScript.scriptRef.log("Enabled logging for " + fn); + } + }, + nuke : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("nuke", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("nuke", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the NUKE.exe virus!"); + } + if (server.openPortCount < server.numOpenPortsRequired) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Not enough ports opened to use NUKE.exe virus"); + } + if (server.hasAdminRights) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { + workerScript.scriptRef.log("Already have root access to " + server.hostname); + } + } else { + server.hasAdminRights = true; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { + workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); + } + } + return true; + }, + brutessh : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("brutessh", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("brutessh", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram)) { + workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the BruteSSH.exe program!"); + } + if (!server.sshPortOpen) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { + workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); + } + server.sshPortOpen = true; + ++server.openPortCount; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { + workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); + } + } + return true; + }, + ftpcrack : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("ftpcrack", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("ftpcrack", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the FTPCrack.exe program!"); + } + if (!server.ftpPortOpen) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { + workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); + } + server.ftpPortOpen = true; + ++server.openPortCount; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { + workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); + } + } + return true; + }, + relaysmtp : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("relaysmtp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("relaysmtp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the relaySMTP.exe program!"); + } + if (!server.smtpPortOpen) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { + workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); + } + server.smtpPortOpen = true; + ++server.openPortCount; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { + workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); + } + } + return true; + }, + httpworm : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("httpworm", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("httpworm", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the HTTPWorm.exe program!"); + } + if (!server.httpPortOpen) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { + workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); + } + server.httpPortOpen = true; + ++server.openPortCount; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { + workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); + } + } + return true; + }, + sqlinject : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("sqlinject", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + } + updateDynamicRam("sqlinject", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); + } + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the SQLInject.exe program!"); + } + if (!server.sqlPortOpen) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { + workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); + } + server.sqlPortOpen = true; + ++server.openPortCount; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { + workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); + } + } + return true; + }, + run : function(scriptname,threads = 1){ + if (workerScript.checkingRam) { + return updateStaticRam("run", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptRunRamCost); + } + updateDynamicRam("run", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptRunRamCost); + if (scriptname === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); + } + if (isNaN(threads) || threads < 1) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); + } + var argsForNewScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForNewScript.push(arguments[i]); + } + var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); + }, + exec : function(scriptname,ip,threads = 1) { + if (workerScript.checkingRam) { + return updateStaticRam("exec", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptExecRamCost); + } + updateDynamicRam("exec", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptExecRamCost); + if (scriptname === undefined || ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); + } + if (isNaN(threads) || threads < 1) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); + } + var argsForNewScript = []; + for (var i = 3; i < arguments.length; ++i) { + argsForNewScript.push(arguments[i]); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["runScriptFromScript"])(server, scriptname, argsForNewScript, workerScript, threads); + }, + spawn : function(scriptname, threads) { + if (workerScript.checkingRam) { + return updateStaticRam("spawn", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSpawnRamCost); + } + updateDynamicRam("spawn", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSpawnRamCost); + if (scriptname == null || threads == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()"); + } + setTimeout(()=>{ + NetscriptFunctions(workerScript).run.apply(this, arguments); + }, 20000); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) { + workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds"); + } + NetscriptFunctions(workerScript).exit(); + }, + kill : function(filename,ip) { + if (workerScript.checkingRam) { + return updateStaticRam("kill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + } + updateDynamicRam("kill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + if (filename === undefined || ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); + } + var argsForKillTarget = []; + for (var i = 2; i < arguments.length; ++i) { + argsForKillTarget.push(arguments[i]); + } + var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(filename, argsForKillTarget, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget)); + return false; + } + var res = Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(runningScriptObj, server.ip); + if (res) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { + workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); + } + return true; + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { + workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget)); + } + return false; + } + }, + killall : function(ip=workerScript.serverIp){ + if (workerScript.checkingRam) { + return updateStaticRam("killall", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + } + updateDynamicRam("killall", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); + } + var scriptsRunning = (server.runningScripts.length > 0); + for (var i = server.runningScripts.length-1; i >= 0; --i) { + Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(server.runningScripts[i], server.ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) { + workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); + } + return scriptsRunning; + }, + exit : function() { + if (workerScript.checkingRam) { + return updateStaticRam("exit", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + } + updateDynamicRam("exit", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev"); + } + if (Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(workerScript.scriptRef, server.ip)) { + workerScript.scriptRef.log("Exiting..."); + } else { + workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer"); + } + }, + scp : function(scriptname, ip1, ip2) { + if (workerScript.checkingRam) { + return updateStaticRam("scp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScpRamCost); + } + updateDynamicRam("scp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScpRamCost); + if (arguments.length !== 2 && arguments.length !== 3) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + if (scriptname && scriptname.constructor === Array) { + //Recursively call scp on all elements of array + var res = false; + scriptname.forEach(function(script) { + if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { + res = true; + }; + }); + return res; + } + if (!scriptname.endsWith(".lit") && !Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["isScriptFilename"])(scriptname) && + !scriptname.endsWith("txt")) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() does not work with this file type. It only works for .script, .lit, and .txt files"); + } + + var destServer, currServ; + + if (arguments.length === 3) { //scriptname, source, destination + if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip2); + if (destServer == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); + } + + currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip1); + if (currServ == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); + } + } else if (arguments.length === 2) { //scriptname, destination + if (scriptname === undefined || ip1 === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); + } + destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip1); + if (destServer == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); + } + + currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (currServ == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); + } + } + + //Scp for lit files + if (scriptname.endsWith(".lit")) { + var found = false; + for (var i = 0; i < currServ.messages.length; ++i) { + if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && currServ.messages[i] == scriptname) { + found = true; + break; + } + } + + if (!found) { + workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); + return false; + } + + for (var i = 0; i < destServer.messages.length; ++i) { + if (destServer.messages[i] === scriptname) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + } + return true; //Already exists + } + } + destServer.messages.push(scriptname); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + } + return true; + } + + //Scp for text files + if (scriptname.endsWith(".txt")) { + var found = false, txtFile; + for (var i = 0; i < currServ.textFiles.length; ++i) { + if (currServ.textFiles[i].fn === scriptname) { + found = true; + txtFile = currServ.textFiles[i]; + break; + } + } + + if (!found) { + workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); + return false; + } + + for (var i = 0; i < destServer.textFiles.length; ++i) { + if (destServer.textFiles[i].fn === scriptname) { + //Overwrite + destServer.textFiles[i].text = txtFile.text; + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + } + return true; + } + } + var newFile = new _TextFile_js__WEBPACK_IMPORTED_MODULE_22__["TextFile"](txtFile.fn, txtFile.text); + destServer.textFiles.push(newFile); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + } + return true; + } + + //Scp for script files + var sourceScript = null; + for (var i = 0; i < currServ.scripts.length; ++i) { + if (scriptname == currServ.scripts[i].filename) { + sourceScript = currServ.scripts[i]; + break; + } + } + if (sourceScript == null) { + workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); + return false; + } + + //Overwrite script if it already exists + for (var i = 0; i < destServer.scripts.length; ++i) { + if (scriptname == destServer.scripts[i].filename) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); + workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); + } + var oldScript = destServer.scripts[i]; + oldScript.code = sourceScript.code; + oldScript.ramUsage = sourceScript.ramUsage; + return true; + } + } + + //Create new script if it does not already exist + var newScript = new _Script_js__WEBPACK_IMPORTED_MODULE_16__["Script"](); + newScript.filename = scriptname; + newScript.code = sourceScript.code; + newScript.ramUsage = sourceScript.ramUsage; + newScript.server = destServer.ip; + destServer.scripts.push(newScript); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { + workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); + } + return true; + }, + ls : function(ip, grep) { + if (workerScript.checkingRam) { + return updateStaticRam("ls", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); + } + updateDynamicRam("ls", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost); + if (ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); + } + + //Get the grep filter, if one exists + var filter = false; + if (arguments.length >= 2) { + filter = grep.toString(); + } + + var allFiles = []; + for (var i = 0; i < server.programs.length; i++) { + if (filter) { + if (server.programs[i].includes(filter)) { + allFiles.push(server.programs[i]); + } + } else { + allFiles.push(server.programs[i]); + } + } + for (var i = 0; i < server.scripts.length; i++) { + if (filter) { + if (server.scripts[i].filename.includes(filter)) { + allFiles.push(server.scripts[i].filename); + } + } else { + allFiles.push(server.scripts[i].filename); + } + + } + for (var i = 0; i < server.messages.length; i++) { + if (filter) { + if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) { + if (server.messages[i].filename.includes(filter)) { + allFiles.push(server.messages[i].filename); + } + } else if (server.messages[i].includes(filter)) { + allFiles.push(server.messages[i]); + } + } else { + if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) { + allFiles.push(server.messages[i].filename); + } else { + allFiles.push(server.messages[i]); + } + } + } + + for (var i = 0; i < server.textFiles.length; i++) { + if (filter) { + if (server.textFiles[i].fn.includes(filter)) { + allFiles.push(server.textFiles[i].fn); + } + } else { + allFiles.push(server.textFiles[i].fn); + } + } + + //Sort the files alphabetically then print each + allFiles.sort(); + return allFiles; + }, + hasRootAccess : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("hasRootAccess", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHasRootAccessRamCost); + } + updateDynamicRam("hasRootAccess", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHasRootAccessRamCost); + if (ip===undefined){ + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null){ + workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); + } + return server.hasAdminRights; + }, + getIp : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getIp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); + } + updateDynamicRam("getIp", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); + var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + return scriptServer.ip; + }, + getHostname : function(){ + if (workerScript.checkingRam) { + return updateStaticRam("getHostname", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); + } + updateDynamicRam("getHostname", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost); + var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (scriptServer == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); + } + return scriptServer.hostname; + }, + getHackingLevel : function(){ + if (workerScript.checkingRam) { + return updateStaticRam("getHackingLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackingLevelRamCost); + } + updateDynamicRam("getHackingLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackingLevelRamCost); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].updateSkillLevels(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) { + workerScript.scriptRef.log("getHackingLevel() returned " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill); + } + return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill; + }, + getHackingMultipliers : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getHackingMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + } + updateDynamicRam("getHackingMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + return { + chance: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_chance_mult, + speed: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_speed_mult, + money: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_money_mult, + growth: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_grow_mult, + }; + }, + getHacknetMultipliers : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getHacknetMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + } + updateDynamicRam("getHacknetMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + return { + production: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_money_mult, + purchaseCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_purchase_cost_mult, + ramCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_ram_cost_mult, + coreCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_core_cost_mult, + levelCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_level_cost_mult, + }; + }, + getBitNodeMultipliers: function() { + if (workerScript.checkingRam) { + return updateStaticRam("getBitNodeMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + } + updateDynamicRam("getBitNodeMultipliers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost); + if (!hasAISF) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); + } + let copy = Object.assign({}, _BitNode_js__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"]); + return copy; + }, + getServerMoneyAvailable : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("getServerMoneyAvailable", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerMoneyAvailable", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); + } + if (server.hostname == "home") { + //Return player's money + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { + workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.toNumber(), 2)); + } + return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.toNumber(); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { + workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname); + } + return server.moneyAvailable; + }, + getServerSecurityLevel : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("getServerSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) { + workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname); + } + return server.hackDifficulty; + }, + getServerBaseSecurityLevel : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("getServerBaseSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerBaseSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) { + workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname); + } + return server.baseDifficulty; + }, + getServerMinSecurityLevel : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getServerMinSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerMinSecurityLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) { + workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname); + } + return server.minDifficulty; + }, + getServerRequiredHackingLevel : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getServerRequiredHackingLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerRequiredHackingLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) { + workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname); + } + return server.requiredHackingSkill; + }, + getServerMaxMoney : function(ip){ + if (workerScript.checkingRam) { + return updateStaticRam("getServerMaxMoney", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerMaxMoney", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) { + workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname); + } + return server.moneyMax; + }, + getServerGrowth : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getServerGrowth", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerGrowth", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) { + workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname); + } + return server.serverGrowth; + }, + getServerNumPortsRequired : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getServerNumPortsRequired", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerNumPortsRequired", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) { + workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname); + } + return server.numOpenPortsRequired; + }, + getServerRam : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getServerRam", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("getServerRam", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) { + workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.ramUsed, 2) + "GB]"); + } + return [server.maxRam, server.ramUsed]; + }, + serverExists : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("serverExists", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + } + updateDynamicRam("serverExists", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost); + return (Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip) !== null); + }, + fileExists : function(filename,ip=workerScript.serverIp) { + if (workerScript.checkingRam) { + return updateStaticRam("fileExists", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptFileExistsRamCost); + } + updateDynamicRam("fileExists", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptFileExistsRamCost); + if (filename === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.scripts.length; ++i) { + if (filename == server.scripts[i].filename) { + return true; + } + } + for (var i = 0; i < server.programs.length; ++i) { + if (filename.toLowerCase() == server.programs[i].toLowerCase()) { + return true; + } + } + for (var i = 0; i < server.messages.length; ++i) { + if (!(server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && + filename.toLowerCase() === server.messages[i]) { + return true; + } + } + var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(filename, server); + if (txtFile != null) { + return true; + } + return false; + }, + isRunning : function(filename,ip) { + if (workerScript.checkingRam) { + return updateStaticRam("isRunning", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptIsRunningRamCost); + } + updateDynamicRam("isRunning", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptIsRunningRamCost); + if (filename === undefined || ip === undefined) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); + } + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); + } + var argsForTargetScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForTargetScript.push(arguments[i]); + } + return (Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(filename, argsForTargetScript, server) != null); + }, + getNextHacknetNodeCost : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getNextHacknetNodeCost", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); + } + updateDynamicRam("getNextHacknetNodeCost", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); + return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__["getCostOfNextHacknetNode"])(); + }, + + purchaseHacknetNode : function() { + if (workerScript.checkingRam) { + return updateStaticRam("purchaseHacknetNode", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); + } + updateDynamicRam("purchaseHacknetNode", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost); + return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__["purchaseHacknet"])(); + }, + getStockPrice : function(symbol) { + if (workerScript.checkingRam) { + return updateStaticRam("getStockPrice", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); + } + updateDynamicRam("getStockPrice", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPrice()"); + } + return parseFloat(stock.price.toFixed(3)); + }, + getStockPosition : function(symbol) { + if (workerScript.checkingRam) { + return updateStaticRam("getStockPosition", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); + } + updateDynamicRam("getStockPosition", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPosition()"); + } + return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; + }, + buyStock : function(symbol, shares) { + if (workerScript.checkingRam) { + return updateStaticRam("buyStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("buyStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into buyStock()"); + } + if (shares < 0 || isNaN(shares)) { + workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()"); + return 0; + } + shares = Math.round(shares); + if (shares === 0) {return 0;} + + var totalPrice = stock.price * shares; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission)) { + workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + + symbol + ". Need $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission, 2).toString()); + return 0; + } + + var origTotal = stock.playerShares * stock.playerAvgPx; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShares += shares; + stock.playerAvgPx = newTotal / stock.playerShares; + if (_engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { + Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["updateStockPlayerPosition"])(stock); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) { + workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(stock.price, 2) + " per share"); + } + return stock.price; + }, + sellStock : function(symbol, shares) { + if (workerScript.checkingRam) { + return updateStaticRam("sellStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("sellStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into sellStock()"); + } + if (shares < 0 || isNaN(shares)) { + workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()"); + return 0; + } + shares = Math.round(shares); + if (shares > stock.playerShares) {shares = stock.playerShares;} + if (shares === 0) {return 0;} + var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainMoney(gains); + + //Calculate net profit and add to script stats + var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; + if (isNaN(netProfit)) {netProfit = 0;} + workerScript.scriptRef.onlineMoneyMade += netProfit; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug += netProfit; + + stock.playerShares -= shares; + if (stock.playerShares == 0) { + stock.playerAvgPx = 0; + } + if (_engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { + Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["updateStockPlayerPosition"])(stock); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) { + workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(stock.price, 2) + " per share. Gained " + + "$" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(gains, 2)); + } + return stock.price; + }, + shortStock(symbol, shares) { + if (workerScript.checkingRam) { + return updateStaticRam("shortStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("shortStock", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); + } + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); + } + var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["shortStock"])(stock, shares, workerScript); + return res ? stock.price : 0; + }, + sellShort(symbol, shares) { + if (workerScript.checkingRam) { + return updateStaticRam("sellShort", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("sellShort", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); + } + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); + } + var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["sellShort"])(stock, shares, workerScript); + return res ? stock.price : 0; + }, + placeOrder(symbol, shares, price, type, pos) { + if (workerScript.checkingRam) { + return updateStaticRam("placeOrder", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("placeOrder", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); + } + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); + } + var orderType, orderPos; + type = type.toLowerCase(); + if (type.includes("limit") && type.includes("buy")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitBuy; + } else if (type.includes("limit") && type.includes("sell")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitSell; + } else if (type.includes("stop") && type.includes("buy")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopBuy; + } else if (type.includes("stop") && type.includes("sell")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopSell; + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); + } + + pos = pos.toLowerCase(); + if (pos.includes("l")) { + orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Long; + } else if (pos.includes('s')) { + orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Short; + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); + } + + return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["placeOrder"])(stock, shares, price, orderType, orderPos, workerScript); + }, + cancelOrder(symbol, shares, price, type, pos) { + if (workerScript.checkingRam) { + return updateStaticRam("cancelOrder", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + } + updateDynamicRam("cancelOrder", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { + if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); + } + } + var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; + if (stock == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); + } + if (isNaN(shares) || isNaN(price)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); + } + var orderType, orderPos; + type = type.toLowerCase(); + if (type.includes("limit") && type.includes("buy")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitBuy; + } else if (type.includes("limit") && type.includes("sell")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitSell; + } else if (type.includes("stop") && type.includes("buy")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopBuy; + } else if (type.includes("stop") && type.includes("sell")) { + orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopSell; + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); + } + + pos = pos.toLowerCase(); + if (pos.includes("l")) { + orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Long; + } else if (pos.includes('s')) { + orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Short; + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); + } + var params = { + stock: stock, + shares: shares, + price: price, + type: orderType, + pos: orderPos + }; + return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["cancelOrder"])(params, workerScript); + }, + purchaseServer : function(hostname, ram) { + if (workerScript.checkingRam) { + return updateStaticRam("purchaseServer", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + } + updateDynamicRam("purchaseServer", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + var hostnameStr = String(hostname); + hostnameStr = hostnameStr.replace(/\s+/g, ''); + if (hostnameStr == "") { + workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()"); + return ""; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.length >= _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit) { + workerScript.scriptRef.log("Error: You have reached the maximum limit of " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit + + " servers. You cannot purchase any more."); + return ""; + } + + ram = Math.round(ram); + if (isNaN(ram) || !Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["powerOfTwo"])(ram)) { + workerScript.scriptRef.log("Error: purchaseServer() failed due to invalid ram argument. Must be numeric and a power of 2"); + return ""; + } + + if (ram > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam) { + workerScript.scriptRef.log("Error: purchasedServer() failed because specified RAM was too high. Maximum RAM on a purchased server is " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam + "GB"); + return ""; + } + + var cost = ram * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(cost)) { + workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(cost, 2)); + return ""; + } + var newServ = new _Server_js__WEBPACK_IMPORTED_MODULE_17__["Server"]({ + ip: Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__["createRandomIp"])(), + hostname: hostnameStr, + organizationName: "", + isConnectedTo: false, + adminRights: true, + purchasedByPlayer: true, + maxRam: ram, + }); + Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["AddToAllServers"])(newServ); + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.push(newServ.ip); + var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); + homeComputer.serversOnNetwork.push(newServ.ip); + newServ.serversOnNetwork.push(homeComputer.ip); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(cost); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) { + workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(cost, 2)); + } + return newServ.hostname; + }, + deleteServer : function(hostname) { + if (workerScript.checkingRam) { + return updateStaticRam("deleteServer", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + } + updateDynamicRam("deleteServer", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + var hostnameStr = String(hostname); + hostnameStr = hostnameStr.replace(/\s\s+/g, ''); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["GetServerByHostname"])(hostnameStr); + if (server == null) { + workerScript.scriptRef.log("Error: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); + return false; + } + + if (!server.purchasedByPlayer || server.hostname === "home") { + workerScript.scriptRef.log("Error: Server " + server.hostname + " is not a purchased server. " + + "Cannot be deleted. deleteServer() failed"); + return false; + } + + var ip = server.ip; + + //Can't delete server you're currently connected to + if (server.isConnectedTo) { + workerScript.scriptRef.log("Error: deleteServer() failed because you are currently connected to the server you are trying to delete"); + return false; + } + + //A server cannot delete itself + if (ip === workerScript.serverIp) { + workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. deleteServer() failed"); + return false; + } + + //Delete all scripts running on server + if (server.runningScripts.length > 0) { + workerScript.scriptRef.log("Error: Cannot delete server " + server.hostname + " because it still has scripts running."); + return false; + } + + //Delete from player's purchasedServers array + var found = false; + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.length; ++i) { + if (ip == _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers[i]) { + found = true; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.splice(i, 1); + break; + } + } + + if (!found) { + workerScript.scriptRef.log("Error: Could not identify server " + server.hostname + + "as a purchased server. This is likely a bug please contact game dev"); + return false; + } + + //Delete from all servers + delete _Server_js__WEBPACK_IMPORTED_MODULE_17__["AllServers"][ip]; + + //Delete from home computer + found = false; + var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); + for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { + if (ip == homeComputer.serversOnNetwork[i]) { + homeComputer.serversOnNetwork.splice(i, 1); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) { + workerScript.scriptRef.log("Deleted server " + hostnameStr); + } + return true; + } + } + //Wasn't found on home computer + workerScript.scriptRef.log("Error: Could not find server " + server.hostname + + "as a purchased server. This is likely a bug please contact game dev"); + return false; + }, + getPurchasedServers : function(hostname=true) { + if (workerScript.checkingRam) { + return updateStaticRam("getPurchasedServers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + } + updateDynamicRam("getPurchasedServers", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost); + var res = []; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.forEach(function(ip) { + if (hostname) { + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); + } + res.push(server.hostname); + } else { + res.push(ip); + } + }); + return res; + }, + write : function(port, data="", mode="a") { + if (workerScript.checkingRam) { + return updateStaticRam("write", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + } + updateDynamicRam("write", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + if (!isNaN(port)) { //Write to port + //Port 1-10 + port = Math.round(port); + if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); + } + var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; + if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); + } + return port.write(data); + } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Write to text file + var fn = port; + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); + } + var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); + if (txtFile == null) { + txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["createTextFile"])(fn, data, server); + return true; + } + if (mode === "w") { + txtFile.write(data); + } else { + txtFile.append(data); + } + return true; + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for write: " + port); + } + }, + read : function(port) { + if (workerScript.checkingRam) { + return updateStaticRam("read", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + } + updateDynamicRam("read", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + if (!isNaN(port)) { //Read from port + //Port 1-10 + port = Math.round(port); + if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); + } + var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; + if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); + } + return port.read(); + } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Read from text file + var fn = port; + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); + } + var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); + if (txtFile !== null) { + return txtFile.text; + } else { + return ""; + } + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for read(): " + port); + } + }, + peek : function(port) { + if (workerScript.checkingRam) { + return updateStaticRam("peek", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + } + updateDynamicRam("peek", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + if (isNaN(port)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); + } + port = Math.round(port); + if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); + } + var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; + if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); + } + return port.peek(); + }, + clear : function(port) { + if (workerScript.checkingRam) { + return updateStaticRam("clear", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + } + updateDynamicRam("clear", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + if (!isNaN(port)) { //Clear port + port = Math.round(port); + if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); + } + var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; + if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); + } + return port.clear(); + } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Clear text file + var fn = port; + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (server == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); + } + var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); + if (txtFile != null) { + txtFile.write(""); + } + } else { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for clear(): " + port); + } + return 0; + }, + getPortHandle : function(port) { + if (workerScript.checkingRam) { + return updateStaticRam("getPortHandle", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost * 10); + } + updateDynamicRam("getPortHandle", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost * 10); + if (isNaN(port)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); + } + port = Math.round(port); + if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); + } + var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; + if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); + } + return port; + }, + rm : function(fn) { + if (workerScript.checkingRam) { + return updateStaticRam("rm", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + } + updateDynamicRam("rm", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost); + var s = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); + if (s == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); + } + + if (fn.includes(".exe")) { + for (var i = 0; i < s.programs.length; ++i) { + if (s.programs[i] === fn) { + s.programs.splice(i, 1); + return true; + } + } + } else if (Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["isScriptFilename"])(fn)) { + for (var i = 0; i < s.scripts.length; ++i) { + if (s.scripts[i].filename === fn) { + //Check that the script isnt currently running + for (var j = 0; j < s.runningScripts.length; ++j) { + if (s.runningScripts[j].filename === fn) { + workerScript.scriptRef.log("Cannot delete a script that is currently running!"); + return false; + } + } + s.scripts.splice(i, 1); + return true; + } + } + } else if (fn.endsWith(".lit")) { + for (var i = 0; i < s.messages.length; ++i) { + var f = s.messages[i]; + if (!(f instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(f) && f === fn) { + s.messages.splice(i, 1); + return true; + } + } + } else if (fn.endsWith(".txt")) { + for (var i = 0; i < s.textFiles.length; ++i) { + if (s.textFiles[i].fn === fn) { + s.textFiles.splice(i, 1); + return true; + } + } + } + return false; + }, + scriptRunning : function(scriptname, ip) { + if (workerScript.checkingRam) { + return updateStaticRam("scriptRunning", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); + } + updateDynamicRam("scriptRunning", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.runningScripts.length; ++i) { + if (server.runningScripts[i].filename == scriptname) { + return true; + } + } + return false; + }, + scriptKill : function(scriptname, ip) { + if (workerScript.checkingRam) { + return updateStaticRam("scriptKill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); + } + updateDynamicRam("scriptKill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); + } + var suc = false; + for (var i = 0; i < server.runningScripts.length; ++i) { + if (server.runningScripts[i].filename == scriptname) { + Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(server.runningScripts[i], server.ip); + suc = true; + } + } + return suc; + }, + getScriptName : function() { + if (workerScript.checkingRam) {return 0;} + return workerScript.name; + }, + getScriptRam : function (scriptname, ip=workerScript.serverIp) { + if (workerScript.checkingRam) { + return updateStaticRam("getScriptRam", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + } + updateDynamicRam("getScriptRam", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip); + } + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename == scriptname) { + return server.scripts[i].ramUsage; + } + } + return 0; + }, + getHackTime : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getHackTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + } + updateDynamicRam("getHackTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingTime"])(server); //Returns seconds + }, + getGrowTime : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getGrowTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + } + updateDynamicRam("getGrowTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateGrowTime"])(server) / 1000; //Returns seconds + }, + getWeakenTime : function(ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getWeakenTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + } + updateDynamicRam("getWeakenTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); + } + return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateWeakenTime"])(server) / 1000; //Returns seconds + }, + getScriptIncome : function(scriptname, ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getScriptIncome", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + } + updateDynamicRam("getScriptIncome", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + if (arguments.length === 0) { + //Get total script income + var res = []; + res.push(Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])()); + res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].playtimeSinceLastAug/1000)); + return res; + } else { + //Get income for a particular script + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); + } + var argsForScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForScript.push(arguments[i]); + } + var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(scriptname, argsForScript, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForScript)); + return -1; + } + return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; + } + }, + getScriptExpGain : function(scriptname, ip) { + if (workerScript.checkingRam) { + return updateStaticRam("getScriptExpGain", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + } + updateDynamicRam("getScriptExpGain", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost); + if (arguments.length === 0) { + var total = 0; + for (var i = 0; i < _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"].length; ++i) { + total += (_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"][i].scriptRef.onlineExpGained / _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"][i].scriptRef.onlineRunningTime); + } + return total; + } else { + //Get income for a particular script + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); + if (server == null) { + workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); + } + var argsForScript = []; + for (var i = 2; i < arguments.length; ++i) { + argsForScript.push(arguments[i]); + } + var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(scriptname, argsForScript, server); + if (runningScriptObj == null) { + workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForScript)); + return -1; + } + return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; + } + }, + getTimeSinceLastAug : function() { + if (workerScript.checkingRam) { + return updateStaticRam("getTimeSinceLastAug", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + } + updateDynamicRam("getTimeSinceLastAug", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost); + return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].playtimeSinceLastAug; + }, + prompt : function(txt) { + if (workerScript.checkingRam) {return 0;} + if (_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxOpen"]) { + workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); + return false; + } + if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(txt)) {txt = String(txt);} + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxGetNoButton"])(); + yesBtn.innerHTML = "Yes"; + noBtn.innerHTML = "No"; + return new Promise(function(resolve, reject) { + yesBtn.addEventListener("click", ()=>{ + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxClose"])(); + resolve(true); + }); + noBtn.addEventListener("click", ()=>{ + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxClose"])(); + resolve(false); + }); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxCreate"])(txt); + }); + }, + + /* Singularity Functions */ + universityCourse : function(universityName, className) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("universityCourse", ramCost); + } + updateDynamicRam("universityCourse", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); + return; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { + workerScript.scriptRef.log(txt); + } + } + + var costMult, expMult; + switch(universityName.toLowerCase()) { + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSummitUniversity.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSummitUniversity; + costMult = 4; + expMult = 3; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12RothmanUniversity.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12RothmanUniversity; + costMult = 3; + expMult = 2; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven) { + workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenZBInstituteOfTechnology; + costMult = 5; + expMult = 4; + break; + default: + workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed"); + return false; + } + + var task; + switch(className.toLowerCase()) { + case "Study Computer Science".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassStudyComputerScience; + break; + case "Data Structures".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassDataStructures; + break; + case "Networks".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassNetworks; + break; + case "Algorithms".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassAlgorithms; + break; + case "Management".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassManagement; + break; + case "Leadership".toLowerCase(): + task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassLeadership; + break; + default: + workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, task); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { + workerScript.scriptRef.log("Started " + task + " at " + universityName); + } + return true; + }, + + gymWorkout : function(gymName, stat) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("gymWorkout", ramCost); + } + updateDynamicRam("gymWorkout", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); + return; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { + workerScript.scriptRef.log(txt); + } + } + var costMult, expMult; + switch(gymName.toLowerCase()) { + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumCrushFitnessGym.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumCrushFitnessGym; + costMult = 3; + expMult = 2; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSnapFitnessGym.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { + workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSnapFitnessGym; + costMult = 10; + expMult = 5; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12IronGym.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12IronGym; + costMult = 1; + expMult = 1; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12PowerhouseGym.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { + workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12PowerhouseGym; + costMult = 20; + expMult = 10; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenMilleniumFitnessGym: + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven) { + workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenMilleniumFitnessGym; + costMult = 7; + expMult = 4; + break; + default: + workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed"); + return false; + } + + switch(stat.toLowerCase()) { + case "strength".toLowerCase(): + case "str".toLowerCase(): + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymStrength); + break; + case "defense".toLowerCase(): + case "def".toLowerCase(): + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDefense); + break; + case "dexterity".toLowerCase(): + case "dex".toLowerCase(): + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDexterity); + break; + case "agility".toLowerCase(): + case "agi".toLowerCase(): + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymAgility); + break; + default: + workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); + return false; + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { + workerScript.scriptRef.log("Started training " + stat + " at " + gymName); + } + return true; + }, + + travelToCity(cityname) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("travelToCity", ramCost); + } + updateDynamicRam("travelToCity", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + switch(cityname) { + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum: + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Chongqing: + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12: + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyo: + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Ishima: + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven: + if(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost)) { + workerScript.scriptRef.log("ERROR: not enough money to travel with travelToCity()."); + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: not enough money to travel with travelToCity()."); + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city = cityname; + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) { + workerScript.scriptRef.log("Traveled to " + cityname); + } + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity()."); + return false; + } + }, + + purchaseTor() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("purchaseTor", ramCost); + } + updateDynamicRam("purchaseTor", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"]["Darkweb Server"] != null) { + workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); + return false; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost)) { + workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost); + + var darkweb = new _Server_js__WEBPACK_IMPORTED_MODULE_17__["Server"]({ + ip:Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__["createRandomIp"])(), hostname:"darkweb", organizationName:"", + isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1 + }); + Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["AddToAllServers"])(darkweb); + _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip); + + document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive"); + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip); + darkweb.serversOnNetwork.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().ip); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) { + workerScript.scriptRef.log("You have purchased a Tor router!"); + } + return true; + }, + purchaseProgram(programName) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("purchaseProgram", ramCost); + } + updateDynamicRam("purchaseProgram", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + + if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"]["Darkweb Server"] == null) { + workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed."); + return false; + } + + switch(programName.toLowerCase()) { + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].BruteSSHProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].FTPCrackProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].RelaySMTPProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].HTTPWormProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].SQLInjectProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].DeepScanV1Program); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2.toLowerCase(): + var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].DeepScanV2Program); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { + workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program can be found on your home computer."); + } + } else { + workerScript.scriptRef.log("Not enough money to purchase " + programName); + return false; + } + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram()."); + return false; + } + return true; + }, + getStats : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getStats", ramCost); + } + updateDynamicRam("getStats", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return {}; + } + } + + return { + hacking: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill, + strength: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].strength, + defense: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].defense, + dexterity: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].dexterity, + agility: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].agility, + charisma: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].charisma, + intelligence: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].intelligence + } + }, + getCharacterInformation : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getCharacterInformation", ramCost); + } + updateDynamicRam("getCharacterInformation", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return {}; + } + } + + var companyPositionTitle = ""; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"]) { + companyPositionTitle = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName; + } + return { + bitnode: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN, + company: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyName, + jobTitle: companyPositionTitle, + city: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city, + factions: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factions.slice(), + tor: _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"].hasOwnProperty("Darkweb Server"), + timeWorked: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].timeWorked, + workHackExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workHackExpGained, + workStrExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workStrExpGained, + workDefExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workDefExpGained, + workDexExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workDexExpGained, + workAgiExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workAgiExpGained, + workChaExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workChaExpGained, + workRepGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workRepGained, + workMoneyGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workMoneyGained, + }; + }, + isBusy : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("isBusy", ramCost); + } + updateDynamicRam("isBusy", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return; + } + } + return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking; + }, + stopAction : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 2; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("stopAction", ramCost); + } + updateDynamicRam("stopAction", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 1)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); + return false; + } + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) { + workerScript.scriptRef.log(txt); + } + return true; + } + return false; + }, + upgradeHomeRam : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("upgradeHomeRam", ramCost); + } + updateDynamicRam("upgradeHomeRam", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + //Calculate how many times ram has been upgraded (doubled) + var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().maxRam; + var numUpgrades = Math.log2(currentRam); + + //Calculate cost + //Have cost increase by some percentage each time RAM has been upgraded + var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamHome; + var mult = Math.pow(1.55, numUpgrades); + cost = cost * mult; + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(cost)) { + workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); + return false; + } + + var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); + homeComputer.maxRam *= 2; + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(cost); + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) { + workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); + } + return true; + }, + getUpgradeHomeRamCost : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 2; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getUpgradeHomeRamCost", ramCost); + } + updateDynamicRam("getUpgradeHomeRamCost", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + //Calculate how many times ram has been upgraded (doubled) + var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().maxRam; + var numUpgrades = Math.log2(currentRam); + + //Calculate cost + //Have cost increase by some percentage each time RAM has been upgraded + var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamHome; + var mult = Math.pow(1.55, numUpgrades); + return cost * mult; + }, + workForCompany : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("workForCompany", ramCost); + } + updateDynamicRam("workForCompany", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); + return; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition == "" || !(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"])) { + workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); + return false; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { + workerScript.scriptRef.log(txt); + } + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.isPartTimeJob()) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startWorkPartTime(); + } else { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startWork(); + } + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { + workerScript.scriptRef.log("Began working at " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName); + } + return true; + }, + applyToCompany : function(companyName, field) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("applyToCompany", ramCost); + } + updateDynamicRam("applyToCompany", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (!Object(_Company_js__WEBPACK_IMPORTED_MODULE_5__["companyExists"])(companyName)) { + workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); + return false; + } + + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = companyName; + var res; + switch (field.toLowerCase()) { + case "software": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSoftwareJob(true); + break; + case "software consultant": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSoftwareConsultantJob(true); + break; + case "it": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForItJob(true); + break; + case "security engineer": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSecurityEngineerJob(true); + break; + case "network engineer": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForNetworkEngineerJob(true); + break; + case "business": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForBusinessJob(true); + break; + case "business consultant": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForBusinessConsultantJob(true); + break; + case "security": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSecurityJob(true); + break; + case "agent": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForAgentJob(true); + break; + case "employee": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForEmployeeJob(true); + break; + case "part-time employee": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForPartTimeEmployeeJob(true); + break; + case "waiter": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForWaiterJob(true); + break; + case "part-time waiter": + res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForPartTimeWaiterJob(true); + break; + default: + workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); + return false; + } + //The Player object's applyForJob function can return string with special error messages + if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(res)) { + workerScript.scriptRef.log(res); + return false; + } + if (res) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { + workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName); + } + } else { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { + workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); + } + } + return res; + }, + getCompanyRep : function(companyName) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 2; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getCompanyRep", ramCost); + } + updateDynamicRam("getCompanyRep", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + var company = _Company_js__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; + if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["Company"])) { + workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); + return -1; + } + return company.playerReputation; + }, + getCompanyFavor : function(companyName) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getCompanyFavor", ramCost); + } + updateDynamicRam("getCompanyFavor", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + var company = _Company_js__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; + if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["Company"])) { + workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName); + return -1; + } + return company.favor; + }, + checkFactionInvitations : function() { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("checkFactionInvitations", ramCost); + } + updateDynamicRam("checkFactionInvitations", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + //Make a copy of Player.factionInvitations + return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.slice(); + }, + joinFaction : function(name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("joinFaction", ramCost); + } + updateDynamicRam("joinFaction", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); + return false; + } + + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.includes(name)) { + workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); + return false; + } + + var index = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.indexOf(name); + if (index === -1) { + //Redundant and should never happen... + workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.splice(index, 1); + var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name]; + Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["joinFaction"])(fac); + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) { + workerScript.scriptRef.log("Joined the " + name + " faction."); + } + return true; + }, + workForFaction : function(name, type) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("workForFaction", ramCost); + } + updateDynamicRam("workForFaction", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return false; + } + } + + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); + return; + } + + if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); + return false; + } + + if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factions.includes(name)) { + workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); + return false; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) { + workerScript.scriptRef.log(txt); + } + } + + var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name]; + //Arrays listing factions that allow each time of work + var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", + "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", + "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; + var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", + "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; + var scWkAvailable = ["ECorp", "MegaCorp", + "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", + "OmniTek Incorporated", "Four Sigma", "KuaiGong International", + "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", + "Ishima", "Volhaven", "Speakers for the Dead", + "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; + + switch (type.toLowerCase()) { + case "hacking": + case "hacking contracts": + case "hackingcontracts": + if (!hackAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionHackWork(fac); + workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); + return true; + case "field": + case "fieldwork": + case "field work": + if (!fdWkAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionFieldWork(fac); + workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); + return true; + case "security": + case "securitywork": + case "security work": + if (!scWkAvailable.includes(fac.name)) { + workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionSecurityWork(fac); + workerScript.scriptRef.log("Started serving as security details for " + fac.name); + return true; + default: + workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); + } + return true; + }, + getFactionRep : function(name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getFactionRep", ramCost); + } + updateDynamicRam("getFactionRep", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return -1; + } + } + + if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); + return -1; + } + + return _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name].playerReputation; + }, + getFactionFavor : function(name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getFactionFavor", ramCost); + } + updateDynamicRam("getFactionFavor", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 2)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); + return -1; + } + } + + if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { + workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist."); + return -1; + } + + return _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name].favor; + }, + createProgram : function(name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("createProgram", ramCost); + } + updateDynamicRam("createProgram", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); + return; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { + workerScript.scriptRef.log(txt); + } + } + + switch(name.toLowerCase()) { + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram.toLowerCase(): + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerFiveMinutes, 1); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 50) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerFiveMinutes * 2, 50); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 100) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerHalfHour, 100); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 250) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer2Hours, 250); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 500) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer4Hours, 500); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 750) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer8Hours, 750); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 75) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerQuarterHour, 75); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 400) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer2Hours, 400); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].ServerProfiler.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 75) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].ServerProfiler, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerHalfHour, 75); + break; + case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].AutoLink.toLowerCase(): + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 25) { + workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].AutoLink, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerQuarterHour, 25); + break; + default: + workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); + return false; + } + workerScript.scriptRef.log("Began creating program: " + name); + return true; + }, + commitCrime : function(crimeRoughName) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("commitCrime", ramCost); + } + updateDynamicRam("commitCrime", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return; + } + } + if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { + workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); + return; + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { + var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { + workerScript.scriptRef.log(txt); + } + } + + //Set Location to slums + switch(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city) { + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSlums; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Chongqing: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].ChongqingSlums; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12Slums; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyo: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyoSlums; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Ishima: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].IshimaSlums; + break; + case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven: + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenSlums; + break; + default: + console.log("Invalid Player.city value"); + } + + const crime = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["findCrime"])(crimeRoughName.toLowerCase()); + if(crime == null) { // couldn't find crime + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into commitCrime(): " + crime); + } + if(workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { + workerScript.scriptRef.log("Attempting to commit crime: "+crime.name+"..."); + } + return crime.commit(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); + }, + getCrimeChance : function(crimeRoughName) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getCrimeChance", ramCost); + } + updateDynamicRam("getCrimeChance", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return; + } + } + + const crime = Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["findCrime"])(crimeRoughName.toLowerCase()); + if(crime == null) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); + } + + return crime.successRate(); + }, + getOwnedAugmentations : function(purchased=false) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getOwnedAugmentations", ramCost); + } + updateDynamicRam("getOwnedAugmentations", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return []; + } + } + var res = []; + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations.length; ++i) { + res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations[i].name); + } + if (purchased) { + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length; ++i) { + res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations[i].name); + } + } + return res; + }, + getAugmentationsFromFaction : function(facname) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getAugmentationsFromFaction", ramCost); + } + updateDynamicRam("getAugmentationsFromFaction", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return []; + } + } + + if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(facname)) { + workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); + return []; + } + + var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][facname]; + var res = []; + for (var i = 0; i < fac.augmentations.length; ++i) { + res.push(fac.augmentations[i]); + } + return res; + }, + getAugmentationCost : function(name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("getAugmentationCost", ramCost); + } + updateDynamicRam("getAugmentationCost", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + if (!Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["augmentationExists"])(name)) { + workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); + return [-1, -1]; + } + + var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; + return [aug.baseRepRequirement, aug.baseCost]; + }, + purchaseAugmentation : function(faction, name) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("purchaseAugmentation", ramCost); + } + updateDynamicRam("purchaseAugmentation", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][faction]; + if (fac == null || !(fac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Faction"])) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); + return false; + } + + if (!fac.augmentations.includes(name)) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); + return false; + } + + var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; + if (aug == null || !(aug instanceof _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentation"])) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); + return false; + } + + var isNeuroflux = false; + if (aug.name === _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["AugmentationNames"].NeuroFluxGovernor) { + isNeuroflux = true; + } + + if (!isNeuroflux) { + for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length; ++j) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations[j].name === aug.name) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); + return false; + } + } + for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations.length; ++j) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations[j].name === aug.name) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); + return false; + } + } + } + + if (fac.playerReputation < aug.baseRepRequirement) { + workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); + return false; + } + + var res = Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["purchaseAugmentation"])(aug, fac, true); + workerScript.scriptRef.log(res); + if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(res) && res.startsWith("You purchased")) { + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + return true; + } else { + return false; + } + }, + installAugmentations : function(cbScript) { + var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} + if (workerScript.checkingRam) { + return updateStaticRam("installAugmentations", ramCost); + } + updateDynamicRam("installAugmentations", ramCost); + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { + if (!(hasSingularitySF && singularitySFLvl >= 3)) { + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); + return false; + } + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length === 0) { + workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); + return false; + } + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); + workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); + Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["installAugmentations"])(cbScript); + return true; + }, + + //Bladeburner API + bladeburner : { + isContractName : function(name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + isOperationName : function(name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + isBlackOpName : function(name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + isGeneralActionName : function(name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + isSkillName : function(name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + startAction : function(type, name) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + stopAction : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getActionTime : function(type="", name="") { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getActionEstimatedSuccessChance : function(type="", name="") { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getActionCountRemaining : function(type="", name="") { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getRank : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getSkillPoints : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getSkillLevel : function(skillName="") { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + upgradeSkill : function(skillName) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getTeamSize : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + setTeamSize : function(type="", name="", size) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getCityEstimatedPopulation : function(cityName) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getCityEstimatedCommunities : function(cityName) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getCityChaos : function(cityName) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + switchCity : function(cityName) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + getStamina : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + }, + joinFaction : function() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { + + } + throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + + "at the Bladeburner division or because you do not have Source-File 7"); + } + } + } //End return +} //End NetscriptFunction() + + + /***/ }), /* 27 */ -/*!****************************!*\ - !*** ./src/Bladeburner.js ***! - \****************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bladeburner", function() { return Bladeburner; }); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./RedPill.js */ 45); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); - - - - - - - - - - - - - - - -var CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"]; - -var CyclesPerSecond = 5; //Game cycle is 200 ms - -var StaminaGainPerSecond = 0.0085; -var BaseStaminaLoss = 0.285; //Base stamina loss per action. Increased based on difficulty -var MaxStaminaToGainFactor = 70000; //Max Stamina is divided by this to get bonus stamina gain - -var DifficultyToTimeFactor = 10; //Action Difficulty divided by this to get base action time - -//The difficulty multiplier affects stamina loss and hp loss of an action. Its formula is: -//difficulty ^ exponentialFactor + difficulty / linearFactor -var DiffMultExponentialFactor = 0.28; -var DiffMultLinearFactor = 670; - -var BaseRecruitmentTimeNeeded = 300; //Base time needed (s) to complete a Recruitment action - -var PopulationThreshold = 1e9; //Population at which success rates start being affected -var ChaosThreshold = 50; //City chaos level after which it starts making tasks harder - -var BaseStatGain = 1; //Base stat gain per second -var BaseIntGain = 0.001; //Base intelligence stat gain - -var ActionCountGrowthPeriod = 300; //Time (s) it takes for action count to grow by its specified value - -var RankToFactionRepFactor = 2; //Delta Faction Rep = this * Delta Rank - -var ContractSuccessesPerLevel = 15; //How many successes you need to level up a contract -var OperationSuccessesPerLevel = 10; //How many successes you need to level up an op - -var RanksPerSkillPoint = 4; //How many ranks needed to get 1 Skill Point - -var ContractBaseMoneyGain = 5e3; //Base Money Gained per contract - -//DOM related variables -var ActiveActionCssClass = "bladeburner-active-action"; - -//Console related stuff -var consoleHistory = []; //Console command history -var consoleHistoryIndex = 0; -var consoleHelpText = { - helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.

" + - "automate [var] [val] [hi/low] Configure simple automation for Bladeburner tasks
" + - "clear/cls Clear the console
" + - "help [cmd] Display this help text, or help text for a specific command
" + - "log [en/dis] [type] Enable or disable logging for events and actions
" + - "skill [action] [name] Level or display info about your Bladeburner skills
" + - "start [type] [name] Start a Bladeburner action/task
" + - "stop Stops your current Bladeburner action/task
", - automate:"automate [var] [val] [hi/low]

" + - "A simple way to automate your Bladeburner actions. This console command can be used " + - "to automatically start an action when your stamina rises above a certain threshold, and " + - "automatically switch to another action when your stamina drops below another threshold.

" + - "automate status - Check the current status of your automation and get a brief description of what it'll do
" + - "automate en - Enable the automation feature
" + - "automate dis - Disable the automation feature

" + - "There are four properties that must be set for this automation to work properly. Here is how to set them:

" + - "automate stamina 100 high
" + - "automate contract Tracking high
" + - "automate stamina 50 low
" + - 'automate general "Field Analysis" low

' + - "Using the four console commands above will set the automation to perform Tracking contracts " + - "if your stamina is 100 or higher, and then switch to Field Analysis if your stamina drops below " + - "50. Note that when setting the action, the name of the action is CASE-SENSITIVE. It must " + - "exactly match whatever the name is in the UI.", - clear:"clear

Clears the console", - cls:"cls

Clears the console", - help:"help [command]

" + - "Running 'help' with no arguments displays the general help text, which lists all console commands " + - "and a brief description of what they do. A command can be specified to get more specific help text " + - "about that particular command. For example:

" + - "help automate

" + - "will display specific information about using the automate console command", - log:"log [en/dis] [type]

" + - "Enable or disable logging. By default, the results of completing actions such as contracts/operations are logged " + - "in the console. There are also random events that are logged in the console as well. The five categories of " + - "things that get logged are:

" + - "[general, contracts, ops, blackops, events]

" + - "The logging for these categories can be enabled or disabled like so:

" + - "log dis contracts - Disables logging that occurs when contracts are completed
" + - "log en contracts - Enables logging that occurs when contracts are completed
" + - "log dis events - Disables logging for Bladeburner random events

" + - "Logging can be universally enabled/disabled using the 'all' keyword:

" + - "log dis all
" + - "log en all", - skill:"skill [action] [name]

" + - "Level or display information about your skills.

" + - "To display information about all of your skills and your multipliers, use:

" + - "skill list

" + - "To display information about a specific skill, specify the name of the skill afterwards. " + - "Note that the name of the skill is case-sensitive. Enter it exactly as seen in the UI. If " + - "the name of the skill has whitespace, enclose the name of the skill in double quotation marks:

" + - "skill list Reaper
" + - 'skill list "Digital Observer"

' + - "This console command can also be used to level up skills:

" + - "skill level [skill name]", - start:"start [type] [name]

" + - "Start an action. An action is specified by its type and its name. The " + - "name is case-sensitive. It must appear exactly as it does in the UI. If " + - "the name of the action has whitespace, enclose it in double quotation marks. " + - "Valid action types include:

" + - "[general, contract, op, blackop]

" + - "Examples:

" + - 'start contract Tracking
' + - 'start op "Undercover Operation"
', - stop:"stop

" + - "Stop your current action and go idle", -} - -//Keypresses for Console -$(document).keydown(function(event) { - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { - //if (DomElems.consoleInput && !event.ctrlKey && !event.shiftKey && !event.altKey) { - // DomElems.consoleInput.focus(); - //} - - if (!(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner instanceof Bladeburner)) {return;} - - //NOTE: Keycodes imported from Terminal.js - if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].ENTER) { - event.preventDefault(); - var command = DomElems.consoleInput.value; - if (command.length > 0) { - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.postToConsole("> " + command); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.resetConsoleInput(); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.executeConsoleCommands(command); - } - } - - if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].UPARROW) { - if (DomElems.consoleInput == null) {return;} - var i = consoleHistoryIndex; - var len = consoleHistory.length; - - if (len === 0) {return;} - if (i < 0 || i > len) { - consoleHistoryIndex = len; - } - - if (i !== 0) { - --consoleHistoryIndex; - } - - var prevCommand = consoleHistory[consoleHistoryIndex]; - DomElems.consoleInput.value = prevCommand; - setTimeout(function(){DomElems.consoleInput.selectionStart = DomElems.consoleInput.selectionEnd = 10000; }, 0); - } - - if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].DOWNARROW) { - if (DomElems.consoleInput == null) {return;} - var i = consoleHistoryIndex; - var len = consoleHistory.length; - - if (len == 0) {return;} - if (i < 0 || i > len) { - consoleHistoryIndex = len; - } - - //Latest command, put nothing - if (i == len || i == len-1) { - consoleHistoryIndex = len; - DomElems.consoleInput.value = ""; - } else { - ++consoleHistoryIndex; - var prevCommand = consoleHistory[consoleHistoryIndex]; - DomElems.consoleInput.value = prevCommand; - } - } - } -}); - -function City(params={}) { - this.name = params.name ? params.name : _Location_js__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12; - - //Synthoid population and estimate - this.pop = params.pop ? params.pop : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(800e6, 1.2*PopulationThreshold); - this.popEst = this.pop * (Math.random() + 0.5); - - //Number of Synthoid communities population and estimate - this.comms = params.comms ? params.comms : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 40); - this.commsEst = this.comms + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-2, 2); - if (this.commsEst < 0) {this.commsEst = 0;} - this.chaos = 0; -} - -City.prototype.improvePopulationEstimateByCount = function(n) { - if (isNaN(n)) {throw new Error("NaN passeed into City.improvePopulationEstimateByCount()");} - if (this.popEst < this.pop) { - this.popEst += n; - if (this.popEst > this.pop) {this.popEst = this.pop;} - } else if (this.popEst > this.pop) { - this.popEst -= n; - if (this.popEst < this.pop) {this.popEst = this.pop;} - } -} - -//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5% -City.prototype.improvePopulationEstimateByPercentage = function(p, skillMult=1) { - p = p*skillMult; - if (isNaN(p)) {throw new Error("NaN passed into City.improvePopulationEstimateByPercentage()");} - if (this.popEst < this.pop) { - ++this.popEst; //In case estimate is 0 - this.popEst *= (1 + (p/100)); - if (this.popEst > this.pop) {this.popEst = this.pop;} - } else if (this.popEst > this.pop) { - this.popEst *= (1 - (p/100)); - if (this.popEst < this.pop) {this.popEst = this.pop;} - } -} - -City.prototype.improveCommunityEstimate = function(n=1) { - if (isNaN(n)) {throw new Error("NaN passed into City.improveCommunityEstimate()");} - if (this.commsEst < this.comms) { - this.commsEst += n; - if (this.commsEst > this.comms) {this.commsEst = this.comms;} - } else if (this.commsEst > this.comms) { - this.commsEst -= n; - if (this.commsEst < this.comms) {this.commsEst = this.comms;} - } -} - -//@params options: -// estChange(int): How much the estimate should change by -// estOffset(int): Add offset to estimate (offset by percentage) -City.prototype.changePopulationByCount = function(n, params={}) { - if (isNaN(n)) {throw new Error("NaN passed into City.changePopulationByCount()");} - this.pop += n; - if (params.estChange && !isNaN(params.estChange)) {this.popEst += params.estChange;} - if (params.estOffset) { - this.popEst = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(this.popEst, params.estOffset); - } - this.popEst = Math.max(this.popEst, 0); -} - -//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5% -//@params options: -// changeEstEqually(bool) - Change the population estimate by an equal amount -// nonZero (bool) - Set to true to ensure that population always changes by at least 1 -City.prototype.changePopulationByPercentage = function(p, params={}) { - if (isNaN(p)) {throw new Error("NaN passed into City.changePopulationByPercentage()");} - if (p === 0) {return;} - var change = Math.round(this.pop * (p/100)); - - //Population always changes by at least 1 - if (params.nonZero && change === 0) { - p > 0 ? change = 1 : change = -1; - } - - this.pop += change; - if (params.changeEstEqually) { - this.popEst += change; - if (this.popEst < 0) {this.popEst = 0;} - } - return change; -} - -City.prototype.changeChaosByCount = function(n) { - if (isNaN(n)) {throw new Error("NaN passed into City.changeChaosByCount()");} - if (n === 0) {return;} - this.chaos += n; - if (this.chaos < 0) {this.chaos = 0;} -} - -//@p is the percentage, not the multiplier (e.g. pass in p = 5 for 5%) -City.prototype.changeChaosByPercentage = function(p) { - if (isNaN(p)) {throw new Error("NaN passed into City.chaosChaosByPercentage()");} - if (p === 0) {return;} - var change = this.chaos * (p/100); - this.chaos += change; - if (this.chaos < 0) {this.chaos = 0;} -} - -City.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("City", this); -} -City.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(City, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.City = City; - -function Skill(params={name:"foo", desc:"foo"}) { - if (params.name) { - this.name = params.name; - } else { - throw new Error("Failed to initialize Bladeburner Skill. No name was specified in ctor"); - } - if (params.desc) { - this.desc = params.desc; - } else { - throw new Error("Failed to initialize Bladeburner Skills. No desc was specified in ctor"); - } - this.baseCost = params.baseCost ? params.baseCost : 1; //Cost is in Skill Points - this.costInc = params.costInc ? params.costInc : 1; //Additive cost increase per level - - if (params.maxLvl) {this.maxLvl = params.maxLvl;} - - //These benefits are additive. So total multiplier will be level (handled externally) times the - //effects below - if (params.successChanceAll) {this.successChanceAll = params.successChanceAll;} - if (params.successChanceStealth) {this.successChanceStealth = params.successChanceStealth;} - if (params.successChanceKill) {this.successChanceKill = params.successChanceKill;} - if (params.successChanceContract) {this.successChanceContract = params.successChanceContract;} - if (params.successChanceOperation) {this.successChanceOperation = params.successChanceOperation;} - - //This multiplier affects everything that increases synthoid population/community estimate - //e.g. Field analysis, Investigation Op, Undercover Op - if (params.successChanceEstimate) {this.successChanceEstimate = params.successChanceEstimate;} - - if (params.actionTime) {this.actionTime = params.actionTime;} - if (params.effHack) {this.effHack = params.effHack;} - if (params.effStr) {this.effStr = params.effStr;} - if (params.effDef) {this.effDef = params.effDef;} - if (params.effDex) {this.effDex = params.effDex;} - if (params.effAgi) {this.effAgi = params.effAgi;} - if (params.effCha) {this.effCha = params.effCha;} - - if (params.stamina) {this.stamina = params.stamina;} - - //Equipment - if (params.weaponAbility) {this.weaponAbility = params.weaponAbility;} - if (params.gunAbility) {this.gunAbility = params.gunAbility;} -} -var Skills = {}; -var SkillNames = { - BladesIntuition: "Blade's Intuition", - Reaper: "Reaper", - Cloak: "Cloak", - Marksman: "Marksman", - WeaponProficiency: "Weapon Proficiency", - Overclock: "Overclock", - EvasiveSystem: "Evasive System", - ShortCircuit: "Short-Circuit", - DigitalObserver: "Digital Observer", - Datamancer: "Datamancer", - Tracer: "Tracer", - CybersEdge: "Cyber's Edge" -} - -//Base Class for Contracts, Operations, and BlackOps -function Action(params={}) { - this.name = params.name ? params.name : ""; - this.desc = params.desc ? params.desc : ""; - - //Difficulty scales with level - //Exact formula is not set in stone - //Initial design: baseDifficulty * (difficultyFac ^ level)? - //difficulty Fac is slightly greater than 1 - this.level = 1; - this.maxLevel = 1; - this.autoLevel = true; - this.baseDifficulty = params.baseDifficulty ? Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(params.baseDifficulty, 10) : 100; - this.difficultyFac = params.difficultyFac ? params.difficultyFac : 1.01; - - //Rank increase/decrease is affected by this exponent - this.rewardFac = params.rewardFac ? params.rewardFac : 1.02; - - this.successes = 0; - this.failures = 0; - - //All of these scale with level/difficulty - this.rankGain = params.rankGain ? params.rankGain : 0; - if (params.rankLoss) {this.rankLoss = params.rankLoss;} - if (params.hpLoss) { - this.hpLoss = params.hpLoss; - this.hpLost = 0; - } - - //Action Category. Current categories are stealth and kill - this.isStealth = params.isStealth ? true : false; - this.isKill = params.isKill ? true : false; - - //Number of this contract remaining, and its growth rate - //Growth rate is an integer and the count will increase by that integer every "cycle" - this.count = params.count ? params.count : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1e3, 25e3); - this.countGrowth = params.countGrowth ? params.countGrowth : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5); - - //Weighting of each stat in determining action success rate - var defaultWeights = {hack:1/7,str:1/7,def:1/7,dex:1/7,agi:1/7,cha:1/7,int:1/7}; - this.weights = params.weights ? params.weights : defaultWeights; - - //Check to make sure weights are summed properly - var sum = 0; - for (var weight in this.weights) { - if (this.weights.hasOwnProperty(weight)) { - sum += this.weights[weight]; - } - } - if (sum - 1 >= 10 * Number.EPSILON) { - throw new Error("Invalid weights when constructing Action " + this.name + - ". The weights should sum up to 1. They sum up to :" + 1); - } - - //Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1) - var defaultDecays = {hack:0.9,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.9,int:0.9}; - this.decays = params.decays ? params.decays : defaultDecays; - for (var decay in this.decays) { - if (this.decays.hasOwnProperty(decay)) { - if (this.decays[decay] > 1) { - throw new Error("Invalid decays when constructing " + - "Action " + this.name + ". " + - "Decay value cannot be greater than 1"); - } - } - } -} - -Action.prototype.getDifficulty = function() { - var difficulty = this.baseDifficulty * Math.pow(this.difficultyFac, this.level-1); - if (isNaN(difficulty)) {throw new Error("Calculated NaN in Action.getDifficulty()");} - return difficulty; -} - -//@inst - Bladeburner Object -//@params - options: -// est (bool): Get success chance estimate instead of real success chance -Action.prototype.getSuccessChance = function(inst, params={}) { - if (inst == null) {throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");} - var difficulty = this.getDifficulty(); - var competence = 0; - for (var stat in this.weights) { - if (this.weights.hasOwnProperty(stat)) { - var playerStatLvl = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queryStatFromString(stat); - var key = "eff" + stat.charAt(0).toUpperCase() + stat.slice(1); - var effMultiplier = inst.skillMultipliers[key]; - if (effMultiplier == null) { - console.log("ERROR: Failed to find Bladeburner Skill multiplier for: " + stat); - effMultiplier = 1; - } - competence += (this.weights[stat] * Math.pow(effMultiplier*playerStatLvl, this.decays[stat])); - } - } - competence *= inst.calculateStaminaPenalty(); - - //For Operations, factor in team members - if (this instanceof Operation || this instanceof BlackOperation) { - if (this.teamCount && this.teamCount > 0) { - this.teamCount = Math.min(this.teamCount, inst.teamSize); - var teamMultiplier = Math.pow(this.teamCount, 0.05); - competence *= teamMultiplier; - } - } - - //Lower city population results in lower chances - if (!(this instanceof BlackOperation)) { - var city = inst.getCurrentCity(); - if (params.est) { - competence *= (city.popEst / PopulationThreshold); - } else { - competence *= (city.pop / PopulationThreshold); - } - - //Too high of a chaos results in lower chances - if (city.chaos > ChaosThreshold) { - var diff = 1 + (city.chaos - ChaosThreshold); - var mult = Math.pow(diff, 0.1); - difficulty *= mult; - } - - //For Raid Operations, no communities = fail - if (this instanceof Operation && this.name === "Raid") { - if (city.comms <= 0) {return 0;} - } - } - - //Factor skill multipliers into success chance - competence *= inst.skillMultipliers.successChanceAll; - if (this instanceof Operation || this instanceof BlackOperation) { - competence *= inst.skillMultipliers.successChanceOperation; - } - if (this instanceof Contract) { - competence *= inst.skillMultipliers.successChanceContract; - } - if (this.isStealth) { - competence *= inst.skillMultipliers.successChanceStealth; - } - if (this.isKill) { - competence *= inst.skillMultipliers.successChanceKill; - } - - //Augmentation multiplier - competence *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_success_chance_mult; - - if (isNaN(competence)) {throw new Error("Competence calculated as NaN in Action.getSuccessChance()");} - return Math.min(1, competence / difficulty); -} - -//Tests for success. Should be called when an action has completed -// @inst - Bladeburner Object -Action.prototype.attempt = function(inst) { - return (Math.random() < this.getSuccessChance(inst)); -} - -Action.prototype.getActionTime = function(inst) { - var difficulty = this.getDifficulty(); - var baseTime = difficulty / DifficultyToTimeFactor; - var skillFac = inst.skillMultipliers.actionTime; //Always < 1 - - var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * inst.skillMultipliers.effAgi; - var effDexterity = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity * inst.skillMultipliers.effDex; - var statFac = 0.5 * (Math.pow(effAgility, 0.03) + Math.pow(effDexterity, 0.03)); //Always > 1 - - baseTime = Math.max(1, baseTime * skillFac / statFac); - - if (this instanceof Contract) { - return Math.ceil(baseTime); - } else if (this instanceof Operation) { - return Math.ceil(baseTime); - } else if (this instanceof BlackOperation) { - return Math.ceil(baseTime * 1.5); - } else { - throw new Error("Unrecognized Action Type in Action.getActionTime(this). Must be either Contract, Operation, or BlackOperation"); - } -} - -Action.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Action", this); -} -Action.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Action, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Action = Action; -var GeneralActions = {}; //Training, Field Analysis, Recruitment, etc. - -//Action Identifier -var ActionTypes = Object.freeze({ - "Idle": 1, - "Contract": 2, - "Operation": 3, - "BlackOp": 4, - "BlackOperation": 4, - "Training": 5, - "Recruitment": 6, - "FieldAnalysis": 7, - "Field Analysis": 7 -}); -function ActionIdentifier(params={}) { - if (params.name) {this.name = params.name;} - if (params.type) {this.type = params.type;} -} -ActionIdentifier.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("ActionIdentifier", this); -} -ActionIdentifier.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(ActionIdentifier, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.ActionIdentifier = ActionIdentifier; - -//Contracts -function Contract(params={}) { - Action.call(this, params); -} -Contract.prototype = Object.create(Action.prototype); -Contract.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Contract", this); -} -Contract.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Contract, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Contract = Contract; - -//Operations -function Operation(params={}) { - Action.call(this, params); - this.reqdRank = params.reqdRank ? params.reqdRank : 100; - this.teamCount = params.teamCount ? params.teamCount : 0; //# of team members to use -} -Operation.prototype = Object.create(Action.prototype); -Operation.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Operation", this); -} -Operation.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Operation, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Operation = Operation; - -//Black Operations -function BlackOperation(params={}) { - Operation.call(this, params); - - //Black ops are one time missions - this.count = 1; - this.countGrowth = 0; -} -BlackOperation.prototype = Object.create(Action.prototype); -BlackOperation.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("BlackOperation", this); -} -BlackOperation.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(BlackOperation, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.BlackOperation = BlackOperation; -var BlackOperations = {}; - -function Bladeburner(params={}) { - this.numHosp = 0; //Number of hospitalizations - this.moneyLost = 0; //Money lost due to hospitalizations - this.rank = 0; - this.maxRank = 0; //Used to determine skill points - - this.skillPoints = 0; - this.totalSkillPoints = 0; - - this.teamSize = 0; //Number of team members - this.teamLost = 0; //Number of team members lost - - this.storedCycles = 0; - - this.randomEventCounter = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 600); //5-10 minutes - - //These times are in seconds - this.actionTimeToComplete = 0; //0 or -1 is an infinite running action (like training) - this.actionTimeCurrent = 0; - - //ActionIdentifier Object - var idleActionType = ActionTypes["Idle"]; - this.action = new ActionIdentifier({type:idleActionType}); - - this.cities = {}; - for (var i = 0; i < CityNames.length; ++i) { - this.cities[CityNames[i]] = new City({name:CityNames[i]}); - } - this.city = _Location_js__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12; - - //Map of SkillNames -> level - this.skills = {}; - this.skillMultipliers = {}; - this.updateSkillMultipliers(); //Calls resetSkillMultipliers() - - //Max Stamina is based on stats and Bladeburner-specific bonuses - this.staminaBonus = 0; //Gained from training - this.maxStamina = 0; - this.calculateMaxStamina(); - this.stamina = this.maxStamina; - - //Contracts and Operations objects. These objects have unique - //properties because they are randomized in each instance and have stats like - //successes/failures, so they need to be saved/loaded by the game. - this.contracts = {}; - this.operations = {}; - - //Object that contains name of all Black Operations that have been completed - this.blackops = {}; - - //Flags for whether these actions should be logged to console - this.logging = { - general:true, - contracts:true, - ops:true, - blackops:true, - events:true, - } - - //Simple automation values - this.automateEnabled = false; - this.automateActionHigh = 0; - this.automateThreshHigh = 0; //Stamina Threshold - this.automateActionLow = 0; - this.automateThreshLow = 0; //Stamina Threshold - - //Initialization - initBladeburner(); - this.initializeDomElementRefs(); - if (params.new) {this.create();} -} - -Bladeburner.prototype.create = function() { - this.contracts["Tracking"] = new Contract({ - name:"Tracking", - desc:"Identify and locate Synthoids. This contract involves reconnaissance " + - "and information-gathering ONLY. Do NOT engage. Stealth is of the utmost importance.

" + - "Successfully completing Tracking contracts will slightly improve your Synthoid population estimate for " + - "whatever city you are currently in.", - baseDifficulty:125,difficultyFac:1.02,rewardFac:1.041, - rankGain:0.3, hpLoss:0.5, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 800), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5), - weights:{hack:0,str:0.05,def:0.05,dex:0.35,agi:0.35,cha:0.1, int:0.05}, - decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.9, int:1}, - isStealth:true - }); - this.contracts["Bounty Hunter"] = new Contract({ - name:"Bounty Hunter", - desc:"Hunt down and capture fugitive Synthoids. These Synthoids are wanted alive.

" + - "Successfully completing a Bounty Hunter contract will lower the population in your " + - "current city, and will also increase its chaos level.", - baseDifficulty:250, difficultyFac:1.04,rewardFac:1.085, - rankGain:0.9, hpLoss:1, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(200, 750), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 3), - weights:{hack:0,str:0.15,def:0.15,dex:0.25,agi:0.25,cha:0.1, int:0.1}, - decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9}, - isKill:true - }); - this.contracts["Retirement"] = new Contract({ - name:"Retirement", - desc:"Hunt down and retire (kill) rogue Synthoids.

" + - "Successfully copmleting a Retirement contract will lower the population in your current " + - "city, and will also increase its chaos level.", - baseDifficulty:200, difficultyFac:1.03, rewardFac:1.065, - rankGain:0.6, hpLoss:1, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 900), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1,4), - weights:{hack:0,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0.1, int:0.1}, - decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9}, - isKill:true - }); - - this.operations["Investigation"] = new Operation({ - name:"Investigation", - desc:"As a field agent, investigate and identify Synthoid " + - "populations, movements, and operations.

Successful " + - "Investigation ops will increase the accuracy of your " + - "synthoid data.

" + - "You will NOT lose HP from failed Investigation ops.", - baseDifficulty:400, difficultyFac:1.03,rewardFac:1.07,reqdRank:25, - rankGain:2, rankLoss:0.2, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(50, 400), countGrowth:1, - weights:{hack:0.25,str:0.05,def:0.05,dex:0.2,agi:0.1,cha:0.25, int:0.1}, - decays:{hack:0.85,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9}, - isStealth:true - }); - this.operations["Undercover Operation"] = new Operation({ - name:"Undercover Operation", - desc:"Conduct undercover operations to identify hidden " + - "and underground Synthoid communities and organizations.

" + - "Successful Undercover ops will increase the accuracy of your synthoid " + - "data.", - baseDifficulty:500, difficultyFac:1.04, rewardFac:1.09, reqdRank:100, - rankGain:4, rankLoss:0.4, hpLoss:2, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(50, 300), countGrowth:1, - weights:{hack:0.2,str:0.05,def:0.05,dex:0.2,agi:0.2,cha:0.2, int:0.1}, - decays:{hack:0.8,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9}, - isStealth:true - }); - this.operations["Sting Operation"] = new Operation({ - name:"Sting Operation", - desc:"Conduct a sting operation to bait and capture particularly " + - "notorious Synthoid criminals.", - baseDifficulty:650, difficultyFac:1.04, rewardFac:1.095, reqdRank:500, - rankGain:5, rankLoss:0.5, hpLoss:2.5, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25,400), countGrowth:0.75, - weights:{hack:0.25,str:0.05,def:0.05,dex:0.25,agi:0.1,cha:0.2, int:0.1}, - decays:{hack:0.8,str:0.85,def:0.85,dex:0.85,agi:0.85,cha:0.7, int:0.9}, - isStealth:true - }); - this.operations["Raid"] = new Operation({ - name:"Raid", - desc:"Lead an assault on a known Synthoid community. Note that " + - "there must be an existing Synthoid community in your current city " + - "in order for this Operation to be successful", - baseDifficulty:800, difficultyFac:1.045, rewardFac:1.1, reqdRank:3000, - rankGain:50,rankLoss:2.5,hpLoss:50, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 150), countGrowth:0.2, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, - isKill:true - }); - this.operations["Stealth Retirement Operation"] = new Operation({ - name:"Stealth Retirement Operation", - desc:"Lead a covert operation to retire Synthoids. The " + - "objective is to complete the task without " + - "drawing any attention. Stealth and discretion are key.", - baseDifficulty:1000, difficultyFac:1.05, rewardFac:1.11, reqdRank:20e3, - rankGain:20, rankLoss:2, hpLoss:10, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 250), countGrowth:0.1, - weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, - decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, - isStealth:true, isKill:true - }); - this.operations["Assassination"] = new Operation({ - name:"Assassination", - desc:"Assassinate Synthoids that have been identified as " + - "important, high-profile social and political leaders " + - "in the Synthoid communities.", - baseDifficulty:1500, difficultyFac:1.06, rewardFac:1.14, reqdRank:50e3, - rankGain:40, rankLoss:4, hpLoss:5, - count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 200), countGrowth:0.1, - weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.8}, - isStealth:true, isKill:true - }); -} - -Bladeburner.prototype.storeCycles = function(numCycles=1) { - this.storedCycles += numCycles; -} - -Bladeburner.prototype.process = function() { - //If the Player starts doing some other actions, set action to idle and alert - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].isWorking) { - if (this.action.type !== ActionTypes["Idle"]) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Your Bladeburner action was cancelled because you started " + - "doing something else"); - } - this.resetAction(); - } - - //A 'tick' for this mechanic is one second (= 5 game cycles) - if (this.storedCycles >= CyclesPerSecond) { - var seconds = Math.floor(this.storedCycles / CyclesPerSecond); - seconds = Math.min(seconds, 5); //Max of 5 'ticks' - this.storedCycles -= seconds * CyclesPerSecond; - - //Stamina - this.calculateMaxStamina(); - this.stamina += (this.calculateStaminaGainPerSecond() * seconds); - this.stamina = Math.min(this.maxStamina, this.stamina); - - //Count increase for contracts/operations - for (var contractName in this.contracts) { - if (this.contracts.hasOwnProperty(contractName)) { - var contract = this.contracts[contractName]; - contract.count += (seconds * contract.countGrowth/ActionCountGrowthPeriod); - } - } - for (var operationName in this.operations) { - if (this.operations.hasOwnProperty(operationName)) { - var op = this.operations[operationName]; - op.count += (seconds * op.countGrowth/ActionCountGrowthPeriod); - } - } - - //Chaos goes down very slowly - for (var i = 0; i < CityNames.length; ++i) { - var city = this.cities[CityNames[i]]; - if (!(city instanceof City)) {throw new Error("Invalid City object when processing passive chaos reduction in Bladeburner.process");} - city.chaos -= (0.0001 * seconds); - city.chaos = Math.max(0, city.chaos); - } - - //Random Events - this.randomEventCounter -= seconds; - if (this.randomEventCounter <= 0) { - this.randomEvent(); - this.randomEventCounter = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 600); - } - - this.processAction(seconds); - - //Automation - if (this.automateEnabled) { - if (this.stamina <= this.automateThreshLow) { - if (this.action.name !== this.automateActionLow.name || this.action.type !== this.automateActionLow.type) { - this.action = this.automateActionLow; - this.startAction(this.action); - } - } else if (this.stamina >= this.automateThreshHigh) { - if (this.action.name !== this.automateActionHigh.name || this.action.type !== this.automateActionHigh.type) { - this.action = this.automateActionHigh; - this.startAction(this.action); - } - } - } - - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { - this.updateContent(); - } - } -} - -Bladeburner.prototype.calculateMaxStamina = function() { - var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * this.skillMultipliers.effAgi; - var maxStamina = (Math.pow(effAgility, 0.8) + this.staminaBonus); - maxStamina *= this.skillMultipliers.stamina; - maxStamina *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_max_stamina_mult; - if (isNaN(maxStamina)) {throw new Error("Max Stamina calculated to be NaN in Bladeburner.calculateMaxStamina()");} - this.maxStamina = maxStamina; -} - -Bladeburner.prototype.calculateStaminaGainPerSecond = function() { - var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * this.skillMultipliers.effAgi; - var maxStaminaBonus = this.maxStamina / MaxStaminaToGainFactor; - var gain = (StaminaGainPerSecond + maxStaminaBonus) * Math.pow(effAgility, 0.17); - return gain * (this.skillMultipliers.stamina * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_stamina_gain_mult); -} - -Bladeburner.prototype.calculateStaminaPenalty = function() { - return Math.min(1, this.stamina / (0.5 * this.maxStamina)); -} - -Bladeburner.prototype.changeRank = function(change) { - if (isNaN(change)) {throw new Error("NaN passed into Bladeburner.changeRank()");} - this.rank += change; - if (this.rank < 0) {this.rank = 0;} - this.maxRank = Math.max(this.rank, this.maxRank); - - var bladeburnersFactionName = "Bladeburners"; - if (Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["factionExists"])(bladeburnersFactionName)) { - var bladeburnerFac = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][bladeburnersFactionName]; - if (!(bladeburnerFac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { - throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button"); - } - if (bladeburnerFac.isMember) { - bladeburnerFac.playerReputation += (RankToFactionRepFactor * change * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult); - } - } - - //Gain skill points. You get 1 every 4 ranks - var rankNeededForSp = (this.totalSkillPoints+1) * RanksPerSkillPoint; - if (this.maxRank >= rankNeededForSp) { - //Calculate how many skill points to gain - var gainedSkillPoints = Math.floor((this.maxRank - rankNeededForSp) / RanksPerSkillPoint + 1); - this.skillPoints += gainedSkillPoints; - this.totalSkillPoints += gainedSkillPoints; - } -} - -Bladeburner.prototype.getCurrentCity = function() { - var city = this.cities[this.city]; - if (!(city instanceof City)) { - throw new Error("Bladeburner.getCurrentCity() did not properly return a City object"); - } - return city; -} - -Bladeburner.prototype.resetSkillMultipliers = function() { - this.skillMultipliers = { - successChanceAll:1, - successChanceStealth:1, - successChanceKill:1, - successChanceContract:1, - successChanceOperation:1, - successChanceEstimate:1, - actionTime:1, - effHack:1, - effStr:1, - effDef:1, - effDex:1, - effAgi:1, - effCha:1, - effInt:1, - stamina:1, - weaponAbility:1, - gunAbility:1, - }; -} - -Bladeburner.prototype.updateSkillMultipliers = function() { - this.resetSkillMultipliers(); - for (var skillName in this.skills) { - if (this.skills.hasOwnProperty(skillName)) { - var skill = Skills[skillName]; - if (skill == null) { - throw new Error("Could not find Skill Object for: " + skillName); - } - var level = this.skills[skillName]; - if (level == null || level <= 0) {continue;} //Not upgraded - - var multiplierNames = Object.keys(this.skillMultipliers); - for (var i = 0; i < multiplierNames.length; ++i) { - var multiplierName = multiplierNames[i]; - if (skill[multiplierName] != null && !isNaN(skill[multiplierName])) { - var value = skill[multiplierName] * level; - var multiplierValue = 1 + (value / 100); - if (multiplierName === "actionTime") { - multiplierValue = 1 - (value / 100); - } - this.skillMultipliers[multiplierName] *= multiplierValue; - } - } - } - } -} - -Bladeburner.prototype.upgradeSkill = function(skill) { - //This does NOT handle deduction of skill points - var skillName = skill.name; - if (this.skills[skillName]) { - ++this.skills[skillName]; - } else { - this.skills[skillName] = 1; - } - if (isNaN(this.skills[skillName]) || this.skills[skillName] < 0) { - throw new Error("Level of Skill " + skillName + " is invalid: " + this.skills[skillName]); - } - this.updateSkillMultipliers(); -} - -Bladeburner.prototype.getActionObject = function(actionId) { - //Given an ActionIdentifier object, returns the corresponding - //Contract, Operation, or BlackOperation object - switch (actionId.type) { - case ActionTypes["Contract"]: - return this.contracts[actionId.name]; - break; - case ActionTypes["Operation"]: - return this.operations[actionId.name]; - break; - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - return BlackOperations[actionId.name]; - break; - default: - return null; - console.log("WARNING: Bladeburner.getActionObject() called with an unexpected " + - "ActionIdentifier type: " + actionId.type); - } -} - -//Sets the player to the "IDLE" action -Bladeburner.prototype.resetAction = function() { - this.action = new ActionIdentifier({type:ActionTypes.Idle}); -} - -Bladeburner.prototype.startAction = function(actionId) { - this.action = actionId; - this.actionTimeCurrent = 0; - switch (actionId.type) { - case ActionTypes["Idle"]: - this.actionTimeToComplete = 0; - break; - case ActionTypes["Contract"]: - try { - var action = this.getActionObject(actionId); - if (action == null) { - throw new Error("Failed to get Contract Object for: " + actionId.name); - } - if (action.count < 1) {return this.resetAction();} - this.actionTimeToComplete = action.getActionTime(this); - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } - break; - case ActionTypes["Operation"]: - try { - var action = this.getActionObject(actionId); - if (action == null) { - throw new Error ("Failed to get Operation Object for: " + actionId.name); - } - if (action.count < 1) {return this.resetAction();} - this.actionTimeToComplete = action.getActionTime(this); - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } - break; - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - try { - var action = this.getActionObject(actionId); - if (action == null) { - throw new Error("Failed to get BlackOperation object for: " + actionId.name); - } - this.actionTimeToComplete = action.getActionTime(this); - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } - break; - case ActionTypes["Training"]: - this.actionTimeToComplete = 30; - break; - case ActionTypes["Recruitment"]: - var effCharisma = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma * this.skillMultipliers.effCha; - var charismaFactor = Math.pow(effCharisma, 0.81) + effCharisma / 90; - var time = Math.max(10, Math.round(BaseRecruitmentTimeNeeded - charismaFactor)); - this.actionTimeToComplete = time; - break; - case ActionTypes["FieldAnalysis"]: - case ActionTypes["Field Analysis"]: - this.actionTimeToComplete = 30; - break; - default: - throw new Error("Invalid Action Type in Bladeburner.startAction(): " + actionId.type); - break; - } -} - -Bladeburner.prototype.processAction = function(seconds) { - if (this.action.type === ActionTypes["Idle"]) {return;} - if (this.actionTimeToComplete <= 0) { - console.log("action.type: " + this.action.type); - throw new Error("Invalid actionTimeToComplete value: " + this.actionTimeToComplete); - } - if (!(this.action instanceof ActionIdentifier)) { - throw new Error("Bladeburner.action is not an ActionIdentifier Object"); - } - - this.actionTimeCurrent += seconds; - if (this.actionTimeCurrent >= this.actionTimeToComplete) { - return this.completeAction(); - } -} - -Bladeburner.prototype.completeAction = function() { - switch (this.action.type) { - case ActionTypes["Contract"]: - case ActionTypes["Operation"]: - try { - var isOperation = (this.action.type === ActionTypes["Operation"]); - var action = this.getActionObject(this.action); - if (action == null) { - throw new Error("Failed to get Contract/Operation Object for: " + this.action.name); - } - var difficulty = action.getDifficulty(); - var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor; - var rewardMultiplier = Math.pow(action.rewardFac, action.level-1); - - //Stamina loss is based on difficulty - this.stamina -= (BaseStaminaLoss * difficultyMultiplier); - if (this.stamina < 0) {this.stamina = 0;} - - //Process Contract/Operation success/failure - if (action.attempt(this)) { - this.gainActionStats(action, true); - ++action.successes; - --action.count; - - //Earn money for contracts - var moneyGain = 0; - if (!isOperation) { - moneyGain = ContractBaseMoneyGain * rewardMultiplier; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainMoney(moneyGain); - } - - if (isOperation) { - action.maxLevel = Math.floor(action.successes / OperationSuccessesPerLevel) + 1; - } else { - action.maxLevel = Math.floor(action.successes / ContractSuccessesPerLevel) + 1; - } - if (action.rankGain) { - var gain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankGain * rewardMultiplier, 10); - this.changeRank(gain); - if (isOperation && this.logging.ops) { - this.log(action.name + " successfully completed! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(gain, 3) + " rank"); - } else if (!isOperation && this.logging.contracts) { - this.log(action.name + " contract successfully completed! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(gain, 3) + " rank and " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(moneyGain).format("$0.000a")); - } - } - isOperation ? this.completeOperation(true) : this.completeContract(true); - } else { - this.gainActionStats(action, false); - ++action.failures; - var loss = 0, damage = 0; - if (action.rankLoss) { - loss = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankLoss * rewardMultiplier, 10); - this.changeRank(-1 * loss); - } - if (action.hpLoss) { - damage = action.hpLoss * difficultyMultiplier; - damage = Math.ceil(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(damage, 10)); - this.hpLost += damage; - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].takeDamage(damage)) { - ++this.numHosp; - this.moneyLost += (_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HospitalCostPerHp * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].max_hp); - } - } - var logLossText = ""; - if (loss > 0) {logLossText += "Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(loss, 3) + " rank.";} - if (damage > 0) {logLossText += "Took " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(damage, 0) + " damage.";} - if (isOperation && this.logging.ops) { - this.log(action.name + " failed! " + logLossText); - } else if (!isOperation && this.logging.contracts) { - this.log(action.name + " contract failed! " + logLossText); - } - isOperation ? this.completeOperation(false) : this.completeContract(false); - } - if (action.autoLevel) {action.level = action.maxLevel;} //Autolevel - this.startAction(this.action); //Repeat action - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } - break; - case ActionTypes["BlackOp"]: - case ActionTypes["BlackOperation"]: - try { - var action = this.getActionObject(this.action); - if (action == null || !(action instanceof BlackOperation)) { - throw new Error("Failed to get BlackOperation Object for: " + this.action.name); - } - var difficulty = action.getDifficulty(); - var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor; - - //Stamina loss is based on difficulty - this.stamina -= (BaseStaminaLoss * difficultyMultiplier); - if (this.stamina < 0) {this.stamina = 0;} - - //Team loss variables - var teamCount = action.teamCount, teamLossMax; - - if (action.attempt(this)) { - this.gainActionStats(action, true); - action.count = 0; - this.blackops[action.name] = true; - var rankGain = 0; - if (action.rankGain) { - rankGain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankGain, 10); - this.changeRank(rankGain); - } - teamLossMax = Math.ceil(teamCount/2); - - //Operation Daedalus - if (action.name === "Operation Daedalus") { - this.resetAction(); - return Object(_RedPill_js__WEBPACK_IMPORTED_MODULE_5__["hackWorldDaemon"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bitNodeN); - } - - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { - this.createActionAndSkillsContent(); - } - - if (this.logging.blackops) { - this.log(action.name + " successful! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(rankGain, 1) + " rank"); - } - } else { - this.gainActionStats(action, false); - var rankLoss = 0, damage = 0; - if (action.rankLoss) { - rankLoss = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankLoss, 10); - this.changeRank(-1 * rankLoss); - } - if (action.hpLoss) { - damage = action.hpLoss * difficultyMultiplier; - damage = Math.ceil(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(damage, 10)); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].takeDamage(damage)) { - ++this.numHosp; - this.moneyLost += (_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HospitalCostPerHp * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].max_hp); - } - } - teamLossMax = Math.floor(teamCount); - - if (this.logging.blackops) { - this.log(action.name + " failed! Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(rankLoss, 1) + " rank and took" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(damage, 0) + " damage"); - } - } - - this.resetAction(); //Stop regardless of success or fail - - //Calculate team lossses - if (teamCount >= 1) { - var losses = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, teamLossMax); - this.teamSize -= losses; - this.teamLost += losses; - if (this.logging.blackops) { - this.log("You lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(losses, 0) + " team members during " + action.name); - } - } - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } - break; - case ActionTypes["Training"]: - this.stamina -= (0.5 * BaseStaminaLoss); - var strExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult, - defExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult, - dexExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult, - agiExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult, - staminaGain = 0.04 * this.skillMultipliers.stamina; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainStrengthExp(strExpGain); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDefenseExp(defExpGain); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDexterityExp(dexExpGain); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainAgilityExp(agiExpGain); - this.staminaBonus += (staminaGain); - if (this.logging.general) { - this.log("Training completed. Gained: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(strExpGain, 1) + " str exp, " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(defExpGain, 1) + " def exp, " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(dexExpGain, 1) + " dex exp, " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(agiExpGain, 1) + " agi exp, " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(staminaGain, 3) + " max stamina"); - } - this.startAction(this.action); //Repeat action - break; - case ActionTypes["FieldAnalysis"]: - case ActionTypes["Field Analysis"]: - //Does not use stamina. Effectiveness depends on hacking, int, and cha - var eff = 0.04 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_skill, 0.3) + - 0.04 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].intelligence, 0.9) + - 0.02 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma, 0.3); - eff *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_analysis_mult; - if (isNaN(eff) || eff < 0) { - throw new Error("Field Analysis Effectiveness calculated to be NaN or negative"); - } - var hackingExpGain = 20 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult, - charismaExpGain = 20 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainHackingExp(hackingExpGain); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainIntelligenceExp(BaseIntGain); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(charismaExpGain); - this.changeRank(0.1); - console.log("DEBUG: Field Analysis effectiveness is " + (eff * this.skillMultipliers.successChanceEstimate)); - this.getCurrentCity().improvePopulationEstimateByPercentage(eff * this.skillMultipliers.successChanceEstimate); - if (this.logging.general) { - this.log("Field analysis completed. Gained 0.1 rank, " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(hackingExpGain, 1) + " hacking exp, and " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(charismaExpGain, 1) + " charisma exp"); - } - this.startAction(this.action); //Repeat action - break; - case ActionTypes["Recruitment"]: - var successChance = Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma, 0.45) / (this.teamSize + 1); - console.log("Bladeburner recruitment success chance: " + successChance); - if (Math.random() < successChance) { - var expGain = 2 * BaseStatGain * this.actionTimeToComplete; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(expGain); - ++this.teamSize; - if (this.logging.general) { - this.log("Successfully recruited a team member! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(expGain, 1) + " charisma exp"); - } - } else { - var expGain = BaseStatGain * this.actionTimeToComplete; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(expGain); - if (this.logging.general) { - this.log("Failed to recruit a team member. Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(expGain, 1) + " charisma exp"); - } - } - this.startAction(this.action); //Repeat action - break; - default: - break; - } -} - -Bladeburner.prototype.completeContract = function(success) { - if (this.action.type !== ActionTypes.Contract) { - throw new Error("completeContract() called even though current action is not a Contract"); - } - var city = this.getCurrentCity(); - if (success) { - switch (this.action.name) { - case "Tracking": - //Increase estimate accuracy by a relatively small amount - city.improvePopulationEstimateByCount(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(100, 1e3)); - break; - case "Bounty Hunter": - city.changePopulationByCount(-1, {estChange:-1}); - city.changeChaosByCount(0.02); - break; - case "Retirement": - city.changePopulationByCount(-1, {estChange:-1}); - city.changeChaosByCount(0.04); - break; - default: - throw new Error("Invalid Action name in completeContract: " + this.action.name); - } - } -} - -Bladeburner.prototype.completeOperation = function(success) { - if (this.action.type !== ActionTypes.Operation) { - throw new Error("completeOperation() called even though current action is not an Operation"); - } - var action = this.getActionObject(this.action); - if (action == null) { - throw new Error("Failed to get Contract/Operation Object for: " + this.action.name); - } - - //Calculate team losses - var teamCount = action.teamCount, max; - if (teamCount >= 1) { - if (success) { - max = Math.ceil(teamCount/2); - } else { - max = Math.floor(teamCount) - } - var losses = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, max); - this.teamSize -= losses; - this.teamLost += losses; - if (this.logging.ops && losses > 0) { - this.log("Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(losses, 0) + " team members during this " + action.name); - } - } - - var city = this.getCurrentCity(); - if (this.logging.ops) { - if (success) { - this.log(action.name + " completed successfully! ") - } else { - - } - } - switch (action.name) { - case "Investigation": - if (success) { - city.improvePopulationEstimateByPercentage(0.4 * this.skillMultipliers.successChanceEstimate); - if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) { - city.improveCommunityEstimate(1); - } - } else { - this.triggerPotentialMigration(this.city, 0.1); - } - break; - case "Undercover Operation": - if (success) { - city.improvePopulationEstimateByPercentage(0.8 * this.skillMultipliers.successChanceEstimate); - if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) { - city.improveCommunityEstimate(1); - } - } else { - this.triggerPotentialMigration(this.city, 0.15); - } - break; - case "Sting Operation": - if (success) { - city.changePopulationByPercentage(-0.1, {changeEstEqually:true, nonZero:true}); - } - city.changeChaosByCount(0.1); - break; - case "Raid": - if (success) { - city.changePopulationByPercentage(-1, {changeEstEqually:true, nonZero:true}); - --city.comms; - --city.commsEst; - } else { - var change = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-3, -1); - city.changePopulationByPercentage(change, {nonZero:true}); - } - city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5)); - break; - case "Stealth Retirement Operation": - if (success) { - city.changePopulationByPercentage(-0.5, {changeEstEqually:true,nonZero:true}); - } - city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-3, -1)); - break; - case "Assassination": - if (success) { - city.changePopulationByCount(-1, {estChange:-1}); - } - city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-5, 5)); - break; - default: - throw new Error("Invalid Action name in completeOperation: " + this.action.name); - } -} - -//Process stat gains from Contracts, Operations, and Black Operations -//@action(Action obj) - Derived action class -//@success(bool) - Whether action was successful -Bladeburner.prototype.gainActionStats = function(action, success) { - var difficulty = action.getDifficulty(); - - //Gain multiplier based on difficulty. If this changes then the - //same variable calculated in completeAction() needs to change too - var difficultyMult = Math.pow(difficulty, 0.21); - - var time = this.actionTimeToComplete; - var successMult = success ? 1 : 0.5; - - var unweightedGain = time * BaseStatGain * successMult * difficultyMult; - var unweightedIntGain = time * BaseIntGain * successMult * difficultyMult; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainHackingExp(unweightedGain * action.weights.hack * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainStrengthExp(unweightedGain * action.weights.str * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDefenseExp(unweightedGain * action.weights.def * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDexterityExp(unweightedGain * action.weights.dex * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainAgilityExp(unweightedGain * action.weights.agi * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(unweightedGain * action.weights.cha * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainIntelligenceExp(unweightedIntGain * action.weights.int); -} - -Bladeburner.prototype.randomEvent = function() { - var chance = Math.random(); - - //Choose random source/destination city for events - var sourceCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; - var sourceCity = this.cities[sourceCityName]; - if (!(sourceCity instanceof City)) { - throw new Error("sourceCity was not a City object in Bladeburner.randomEvent()"); - } - - var destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; - while (destCityName === sourceCityName) { - destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; - } - var destCity = this.cities[destCityName]; - - if (!(sourceCity instanceof City) || !(destCity instanceof City)) { - throw new Error("sourceCity was not a City object in Bladeburner.randomEvent()"); - } - - if (chance <= 0.05) { - //New Synthoid Community, 5% - ++sourceCity.comms; - var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop += count; - if (this.logging.events) { - this.log("Intelligence indicates that a new Synthoid community was formed in a city"); - } - } else if (chance <= 0.1) { - //Synthoid Community Migration, 5% - if (sourceCity.comms <= 0) { - //If no comms in source city, then instead trigger a new Synthoid community event - ++sourceCity.comms; - var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop += count; - if (this.logging.events) { - this.log("Intelligence indicates that a new Synthoid community was formed in a city"); - } - } else { - --sourceCity.comms; - ++destCity.comms; - - //Change pop - var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop -= count; - destCity.pop += count; - - if (this.logging.events) { - this.log("Intelligence indicates that a Synthoid community migrated from " + sourceCityName + " to some other city"); - } - } - } else if (chance <= 0.3) { - //New Synthoids (non community), 20% - var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(8, 24) / 100; - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop += count; - if (this.logging.events) { - this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly"); - } - } else if (chance <= 0.5) { - //Synthoid migration (non community) 20% - this.triggerMigration(sourceCityName); - if (this.logging.events) { - this.log("Intelligence indicates that a large number of Synthoids migrated from " + sourceCityName + " to some other city"); - } - } else if (chance <= 0.7) { - //Synthoid Riots (+chaos), 20% - sourceCity.chaos += 1; - sourceCity.chaos *= (1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(5, 10) / 100); - if (this.logging.events) { - this.log("Tensions between Synthoids and humans lead to riots in " + sourceCityName + "! Chaos increased"); - } - } else if (chance <= 0.9) { - //Less Synthoids, 20% - var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(5, 20) / 100; - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop -= count; - if (this.logging.events) { - this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly"); - } - } - //20% chance of nothing happening -} - -Bladeburner.prototype.triggerPotentialMigration = function(sourceCityName, chance) { - if (chance == null || isNaN(chance)) { - console.log("ERROR: Invalid 'chance' parameter passed into Bladeburner.triggerPotentialMigration()"); - } - if (chance > 1) {chance /= 100;} - if (Math.random() < chance) {this.triggerMigration(sourceCityName);} -} - -Bladeburner.prototype.triggerMigration = function(sourceCityName) { - var destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; - while (destCityName === sourceCityName) { - destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; - } - var destCity = this.cities[destCityName]; - var sourceCity = this.cities[sourceCityName]; - if (destCity == null || sourceCity == null) { - throw new Error("Failed to find City with name: " + destCityName); - } - var rand = Math.random(), percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(3, 15) / 100; - - if (rand < 0.05 && sourceCity.comms > 0) { //5% chance for community migration - percentage *= Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(2, 4); //Migration increases population change - --sourceCity.comms; - ++destCity.comms; - } - var count = Math.round(sourceCity.pop * percentage); - sourceCity.pop -= count; - destCity.pop += count; -} - -var DomElems = {}; - -Bladeburner.prototype.initializeDomElementRefs = function() { - DomElems = { - bladeburnerDiv: null, - - //Main Divs - overviewConsoleParentDiv: null, - - overviewDiv: null, //Overview of stats that stays fixed on left - actionAndSkillsDiv: null, //Panel for different sections (contracts, ops, skills) - currentTab: null, //Contracts, Operations, Black Ops, Skills - - consoleDiv: null, - consoleTable: null, - consoleInputRow: null, //tr - consoleInputCell: null, //td - consoleInputHeader: null, //"> " - consoleInput: null, //Actual input element - - //Overview Content - overviewRank: null, - overviewStamina: null, - overviewStaminaHelpTip: null, - overviewGen1: null, //Stamina Penalty, Team, Hospitalized stats, current city - overviewEstPop: null, - overviewEstPopHelpTip: null, - overviewEstComms: null, - overviewChaos: null, - overviewSkillPoints: null, - overviewAugSuccessMult: null, - overviewAugMaxStaminaMult: null, - overviewAugStaminaGainMult: null, - overviewAugAnalysisMult: null, - - //Actions and Skills Content - actionsAndSkillsDesc: null, - actionsAndSkillsList: null, //ul element of all UI elements in this panel - generalActions: {}, - contracts: {}, - operations: {}, - blackops: {}, - skills: {}, - }; -} - -Bladeburner.prototype.createContent = function() { - DomElems.bladeburnerDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - id:"bladeburner-container", position:"fixed", class:"generic-menupage-container", - }); - - //Parent Div for Overview and Console - DomElems.overviewConsoleParentDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - height:"60%", display:"block", position:"relative", - }); - - //Overview and Action/Skill pane - DomElems.overviewDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - width:"30%", display:"inline-block", border:"1px solid white", - }); - - DomElems.actionAndSkillsDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - height:"60%", width:"70%", display:"block", - border:"1px solid white", margin:"6px", padding:"6px", - }); - - DomElems.currentTab = "general"; - - this.createOverviewContent(); - this.createActionAndSkillsContent(); - - //Console - DomElems.consoleDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-console-div", - clickListener:()=>{ - if (DomElems.consoleInput instanceof Element) { - DomElems.consoleInput.focus(); - } - return false; - } - }); - DomElems.consoleTable = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("table", {class:"bladeburner-console-table"}); - DomElems.consoleInputRow = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("tr", {class:"bladeburner-console-input-row", id:"bladeubrner-console-input-row"}); - DomElems.consoleInputCell = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("td", {class:"bladeburner-console-input-cell"}); - DomElems.consoleInputHeader = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", {innerText:"> "}); - DomElems.consoleInput = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { - type:"text", class:"bladeburner-console-input", tabIndex:1, - onfocus:()=>{DomElems.consoleInput.value = DomElems.consoleInput.value} - }); - - DomElems.consoleInputCell.appendChild(DomElems.consoleInputHeader); - DomElems.consoleInputCell.appendChild(DomElems.consoleInput); - DomElems.consoleInputRow.appendChild(DomElems.consoleInputCell); - DomElems.consoleTable.appendChild(DomElems.consoleInputRow); - DomElems.consoleDiv.appendChild(DomElems.consoleTable); - - DomElems.overviewConsoleParentDiv.appendChild(DomElems.overviewDiv); - DomElems.overviewConsoleParentDiv.appendChild(DomElems.consoleDiv); - DomElems.bladeburnerDiv.appendChild(DomElems.overviewConsoleParentDiv); - DomElems.bladeburnerDiv.appendChild(DomElems.actionAndSkillsDiv); - - document.getElementById("entire-game-container").appendChild(DomElems.bladeburnerDiv); - - this.postToConsole("Bladeburner Console BETA"); - DomElems.consoleInput.focus(); -} - -Bladeburner.prototype.clearContent = function() { - if (DomElems.bladeburnerDiv instanceof Element) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.bladeburnerDiv); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElement"])(DomElems.bladeburnerDiv); - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems); - this.initializeDomElementRefs(); -} - -Bladeburner.prototype.createOverviewContent = function() { - if (DomElems.overviewDiv == null) { - throw new Error("Bladeburner.createOverviewContent() called with DomElems.overviewDiv = null"); - } - - DomElems.overviewRank = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"Rank: ", - display:"inline-block", - tooltip:"Your rank within the Bladeburner division", - }); - - DomElems.overviewStamina = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"inline-block", - }); - - DomElems.overviewStaminaHelpTip = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - innerText:"?", class:"help-tip", - clickListener:()=>{ - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Performing actions will use up your stamina.

" + - "Your max stamina is determined primarily by your agility stat.

" + - "Your stamina gain rate is determined by both your agility and your " + - "max stamina. Higher max stamina leads to a higher gain rate.

" + - "Once your " + - "stamina falls below 50% of its max value, it begins to negatively " + - "affect the success rate of your contracts/operations. This penalty " + - "is shown in the overview panel. If the penalty is 15%, then this means " + - "your success rate would be multipled by 85% (100 - 15).

" + - "Your max stamina and stamina gain rate can also be increased by " + - "training, or through skills and Augmentation upgrades."); - } - }); - - DomElems.overviewGen1 = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - }); - - DomElems.overviewEstPop = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"Est. Synthoid Population: ", - display:"inline-block", - tooltip:"This is your Bladeburner division's estimate of how many Synthoids exist " + - "in your current city." - }); - - DomElems.overviewEstPopHelpTip = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - innerText:"?", class:"help-tip", - clickListener:()=>{ - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("The success rate of your contracts/operations depends on " + - "the population of Synthoids in your current city. " + - "The success rate that is shown to you is only an estimate, " + - "and it is based on your Synthoid population estimate.

" + - "Therefore, it is important that this Synthoid population estimate " + - "is accurate so that you have a better idea of your " + - "success rate for contracts/operations. Certain " + - "actions will increase the accuracy of your population " + - "estimate.

" + - "The Synthoid populations of cities can change due to your " + - "actions or random events. If random events occur, they will " + - "be logged in the Bladeburner Console."); - } - }); - - DomElems.overviewEstComms = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"Est. Synthoid Communities: ", - display:"inline-block", - tooltip:"This is your Bladeburner divison's estimate of how many Synthoid " + - "communities exist in your current city.", - }); - - DomElems.overviewChaos = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"City Chaos: ", - display:"inline-block", - tooltip:"The city's chaos level due to tensions and conflicts between humans and Synthoids. " + - "Having too high of a chaos level can make contracts and operations harder." - }); - - DomElems.overviewSkillPoints = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); - - DomElems.overviewAugSuccessMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); - DomElems.overviewAugMaxStaminaMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); - DomElems.overviewAugStaminaGainMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); - DomElems.overviewAugAnalysisMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); - - - DomElems.overviewDiv.appendChild(DomElems.overviewRank); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); - DomElems.overviewDiv.appendChild(DomElems.overviewStamina); - DomElems.overviewDiv.appendChild(DomElems.overviewStaminaHelpTip); - DomElems.overviewDiv.appendChild(DomElems.overviewGen1); - DomElems.overviewDiv.appendChild(DomElems.overviewEstPop); - DomElems.overviewDiv.appendChild(DomElems.overviewEstPopHelpTip); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); - DomElems.overviewDiv.appendChild(DomElems.overviewEstComms); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); - DomElems.overviewDiv.appendChild(DomElems.overviewChaos); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 2); - DomElems.overviewDiv.appendChild(DomElems.overviewSkillPoints); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); - DomElems.overviewDiv.appendChild(DomElems.overviewAugSuccessMult); - DomElems.overviewDiv.appendChild(DomElems.overviewAugMaxStaminaMult); - DomElems.overviewDiv.appendChild(DomElems.overviewAugStaminaGainMult); - DomElems.overviewDiv.appendChild(DomElems.overviewAugAnalysisMult); - - //Travel to new city button - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); - DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerHTML:"Travel", class:"a-link-button", display:"inline-block", - clickListener:()=>{ - var popupId = "bladeburner-travel-popup-cancel-btn"; - var popupArguments = []; - popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Cancel Button - innerText:"Cancel", class:"a-link-button", - clickListener:()=>{ - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); return false; - } - })) - popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { //Info Text - innerText:"Travel to a different city for your Bladeburner " + - "activities. This does not cost any money. The city you are " + - "in for your Bladeburner duties does not affect " + - "your location in the game otherwise", - })); - for (var i = 0; i < CityNames.length; ++i) { - (function(inst, i) { - popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - //Reusing this css class...it adds a border and makes it - //so that background color changes when you hover - class:"cmpy-mgmt-find-employee-option", - innerText:CityNames[i], - clickListener:()=>{ - inst.city = CityNames[i]; - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); - inst.updateOverviewContent(); - return false; - } - })); - })(this, i); - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, popupArguments); - } - })); - - //Faction button - var bladeburnersFactionName = "Bladeburners"; - if (Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["factionExists"])(bladeburnersFactionName)) { - var bladeburnerFac = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][bladeburnersFactionName]; - if (!(bladeburnerFac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { - throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button"); - } - DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Faction", class:"a-link-button", display:"inline-block", - tooltip:"Apply to the Bladeburner Faction, or go to the faction page if you are already a member", - clickListener:()=>{ - if (bladeburnerFac.isMember) { - _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); - Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(bladeburnersFactionName); - } else { - if (this.rank >= 25) { - Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["joinFaction"])(bladeburnerFac); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Congratulations! You were accepted into the Bladeburners faction"); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.overviewDiv); - this.createOverviewContent(); - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You need a rank of 25 to join the Bladeburners Faction!") - } - } - return false; - } - })); - } - - DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); - DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); - - this.updateOverviewContent(); -} - -Bladeburner.prototype.createActionAndSkillsContent = function() { - if (DomElems.currentTab == null) {DomElems.currentTab = "general";} - - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.actionAndSkillsDiv); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.generalActions); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.contracts); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.operations); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.blackops); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.skills); - - //Navigation buttons - var currTab = DomElems.currentTab.toLowerCase(); - var buttons = ["General", "Contracts", "Operations", "BlackOps", "Skills"]; - for (var i = 0; i < buttons.length; ++i) { - (function(buttons, i, inst, currTab) { - - DomElems.actionAndSkillsDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:buttons[i], - class:currTab === buttons[i].toLowerCase() ? "bladeburner-nav-button-inactive" : "bladeburner-nav-button", - clickListener:()=>{ - DomElems.currentTab = buttons[i].toLowerCase(); - inst.createActionAndSkillsContent(); - return false; - } - })); - }) (buttons, i, this, currTab); - } - - //General info/description for each action - DomElems.actionsAndSkillsDesc = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", margin:"4px", padding:"4px" - }); - - //List for actions/skills - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.actionsAndSkillsList); - DomElems.actionsAndSkillsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("ul"); - - switch(currTab) { - case "general": - this.createGeneralActionsContent(); - break; - case "contracts": - this.createContractsContent(); - break; - case "operations": - this.createOperationsContent(); - break; - case "blackops": - this.createBlackOpsContent(); - break; - case "skills": - this.createSkillsContent(); - break; - default: - throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent"); - } - this.updateContent(); - - DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsDesc); - DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsList); -} - -Bladeburner.prototype.createGeneralActionsContent = function() { - if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { - throw new Error("Bladeburner.createGeneralActionsContent called with either " + - "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); - } - - DomElems.actionsAndSkillsDesc.innerText = - "These are generic actions that will assist you in your Bladeburner " + - "duties. They will not affect your Bladeburner rank in any way." - - for (var actionName in GeneralActions) { - if (GeneralActions.hasOwnProperty(actionName)) { - DomElems.generalActions[actionName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-action", name:actionName - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.generalActions[actionName]); - } - } -} - -Bladeburner.prototype.createContractsContent = function() { - if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { - throw new Error("Bladeburner.createContractsContent called with either " + - "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); - } - - DomElems.actionsAndSkillsDesc.innerHTML = - "Complete contracts in order to increase your Bitburner rank and earn money. " + - "Failing a contract will cause you to lose HP, which can lead to hospitalization.

" + - "You can unlock higher-level contracts by successfully completing them. " + - "Higher-level contracts are more difficult, but grant more rank, experience, and money."; - - for (var contractName in this.contracts) { - if (this.contracts.hasOwnProperty(contractName)) { - DomElems.contracts[contractName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-action", name:contractName - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.contracts[contractName]); - } - } -} - -Bladeburner.prototype.createOperationsContent = function() { - if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { - throw new Error("Bladeburner.createOperationsContent called with either " + - "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); - } - - DomElems.actionsAndSkillsDesc.innerHTML = - "Carry out operations for the Bladeburner division. " + - "Failing an operation will reduce your Bladeburner rank. It will also " + - "cause you to lose HP, which can lead to hospitalization. In general, " + - "operations are harder and more punishing than contracts, " + - "but are also more rewarding.

" + - "Operations can affect the chaos level and Synthoid population of your " + - "current city. The exact effects vary between different Operations.

" + - "For operations, you can use a team. You must first recruit team members. " + - "Having a larger team will improves your chances of success.

" + - "You can unlock higher-level operations by successfully completing them. " + - "Higher-level operations are more difficult, but grant more rank and experience."; - - for (var operationName in this.operations) { - if (this.operations.hasOwnProperty(operationName)) { - DomElems.operations[operationName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-action", name:operationName - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.operations[operationName]); - } - } -} - -Bladeburner.prototype.createBlackOpsContent = function() { - if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { - throw new Error("Bladeburner.createBlackOpsContent called with either " + - "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); - } - - DomElems.actionsAndSkillsDesc.innerHTML = - "Black Operations (Black Ops) are special, one-time covert operations. " + - "Each Black Op must be unlocked successively by completing " + - "the one before it.

" + - "Like normal operations, you may use a team for Black Ops. Failing " + - "a black op will incur heavy HP and rank losses."; - - //Put Black Operations in sequence of required rank - var blackops = []; - for (var blackopName in BlackOperations) { - if (BlackOperations.hasOwnProperty(blackopName)) { - blackops.push(BlackOperations[blackopName]); - } - } - blackops.sort(function(a, b) { - return (a.reqdRank - b.reqdRank); - }); - - for (var i = 0; i < blackops.length; ++i) { - DomElems.blackops[blackops[i].name] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-action", name:blackops[i].name - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.blackops[blackops[i].name]); - if (this.blackops[[blackops[i].name]] == null) {break;} //Can't be found in completed blackops - } -} - -Bladeburner.prototype.createSkillsContent = function() { - if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { - throw new Error("Bladeburner.createSkillsContent called with either " + - "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); - } - - //Display Current multipliers - DomElems.actionsAndSkillsDesc.innerHTML = - "You will gain one skill point every " + RanksPerSkillPoint + " ranks.

" + - "Note that when upgrading a skill, the benefit for that skill is additive. " + - "However, the effects of different skills with each other is multiplicative.

" - var multKeys = Object.keys(this.skillMultipliers); - for (var i = 0; i < multKeys.length; ++i) { - var mult = this.skillMultipliers[multKeys[i]]; - if (mult && mult !== 1) { - mult = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(mult, 3); - switch(multKeys[i]) { - case "successChanceAll": - DomElems.actionsAndSkillsDesc.innerHTML += "Total Success Chance: x" + mult + "
"; - break; - case "successChanceStealth": - DomElems.actionsAndSkillsDesc.innerHTML += "Stealth Success Chance: x" + mult + "
"; - break; - case "successChanceKill": - DomElems.actionsAndSkillsDesc.innerHTML += "Retirement Success Chance: x" + mult + "
"; - break; - case "successChanceContract": - DomElems.actionsAndSkillsDesc.innerHTML += "Contract Success Chance: x" + mult + "
"; - break; - case "successChanceOperation": - DomElems.actionsAndSkillsDesc.innerHTML += "Operation Success Chance: x" + mult + "
"; - break; - case "successChanceEstimate": - DomElems.actionsAndSkillsDesc.innerHTML += "Synthoid Data Estimate: x" + mult + "
"; - break; - case "actionTime": - DomElems.actionsAndSkillsDesc.innerHTML += "Action Time: x" + mult + "
"; - break; - case "effHack": - DomElems.actionsAndSkillsDesc.innerHTML += "Hacking Skill: x" + mult + "
"; - break; - case "effStr": - DomElems.actionsAndSkillsDesc.innerHTML += "Strength: x" + mult + "
"; - break; - case "effDef": - DomElems.actionsAndSkillsDesc.innerHTML += "Defense: x" + mult + "
"; - break; - case "effDex": - DomElems.actionsAndSkillsDesc.innerHTML += "Dexterity: x" + mult + "
"; - break; - case "effAgi": - DomElems.actionsAndSkillsDesc.innerHTML += "Agility: x" + mult + "
"; - break; - case "effCha": - DomElems.actionsAndSkillsDesc.innerHTML += "Charisma: x" + mult + "
"; - break; - case "effInt": - DomElems.actionsAndSkillsDesc.innerHTML += "Intelligence: x" + mult + "
"; - break; - case "stamina": - DomElems.actionsAndSkillsDesc.innerHTML += "Stamina: x" + mult + "
"; - break; - case "weaponAbility": - //DomElems.actionsAndSkillsDesc.innerHTML += - break; - case "gunAbility": - //DomElems.actionsAndSkillsDesc.innerHTML - break; - default: - console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]); - break; - } - } - } - - //Skill Points - DomElems.actionAndSkillsDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerHTML:"
Skill Points: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skillPoints, 0) + "" - })); - - //UI Element for each skill - for (var skillName in Skills) { - if (Skills.hasOwnProperty(skillName)) { - DomElems.skills[skillName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { - class:"bladeburner-action", name:skillName - }); - DomElems.actionsAndSkillsList.appendChild(DomElems.skills[skillName]); - } - } -} - -Bladeburner.prototype.updateContent = function() { - this.updateOverviewContent(); - this.updateActionAndSkillsContent(); -} - -Bladeburner.prototype.updateOverviewContent = function() { - if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) {return;} - DomElems.overviewRank.childNodes[0].nodeValue = "Rank: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.rank, 2); - DomElems.overviewStamina.innerText = "Stamina: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.stamina, 3) + " / " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.maxStamina, 3); - DomElems.overviewGen1.innerHTML = - "Stamina Penalty: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])((1-this.calculateStaminaPenalty())*100, 1) + "%

" + - "Team Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.teamSize, 0) + "
" + - "Team Members Lost: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.teamLost, 0) + "

" + - "Num Times Hospitalized: " + this.numHosp + "
" + - "Money Lost From Hospitalizations: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(this.moneyLost).format("$0.000a") + "

" + - "Current City: " + this.city + "
"; - - DomElems.overviewEstPop.childNodes[0].nodeValue = "Est. Synthoid Population: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(this.getCurrentCity().popEst).format("0.000a"); - DomElems.overviewEstComms.childNodes[0].nodeValue = "Est. Synthoid Communities: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.getCurrentCity().comms, 0); - DomElems.overviewChaos.childNodes[0].nodeValue = "City Chaos: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.getCurrentCity().chaos); - DomElems.overviewSkillPoints.innerText = "Skill Points: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skillPoints, 0); - DomElems.overviewAugSuccessMult.innerText = "Aug. Success Chance Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_success_chance_mult*100, 1) + "%"; - DomElems.overviewAugMaxStaminaMult.innerText = "Aug. Max Stamina Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_max_stamina_mult*100, 1) + "%"; - DomElems.overviewAugStaminaGainMult.innerText = "Aug. Stamina Gain Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_stamina_gain_mult*100, 1) + "%"; - DomElems.overviewAugAnalysisMult.innerText = "Aug. Field Analysis Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_analysis_mult*100, 1) + "%"; -} - -Bladeburner.prototype.updateActionAndSkillsContent = function() { - if (DomElems.currentTab == null) {DomElems.currentTab = "general";} - switch(DomElems.currentTab.toLowerCase()) { - case "general": - var actionElems = Object.keys(DomElems.generalActions); - for (var i = 0; i < actionElems.length; ++i) { - var actionElem = DomElems.generalActions[actionElems[i]]; - var name = actionElem.name; - var actionObj = GeneralActions[name]; - if (actionObj == null) { - throw new Error("Could not find Object " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - if (this.action.type === ActionTypes[name]) { - actionElem.classList.add(ActiveActionCssClass); - } else { - actionElem.classList.remove(ActiveActionCssClass); - } - this.updateGeneralActionsUIElement(actionElem, actionObj); - } - break; - case "contracts": - var contractElems = Object.keys(DomElems.contracts); - for (var i = 0; i < contractElems.length; ++i) { - var contractElem = DomElems.contracts[contractElems[i]]; - var name = contractElem.name; - if (this.action.type === ActionTypes["Contract"] && name === this.action.name) { - contractElem.classList.add(ActiveActionCssClass); - } else { - contractElem.classList.remove(ActiveActionCssClass); - } - var contract = this.contracts[name]; - if (contract == null) { - throw new Error("Could not find Contract " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateContractsUIElement(contractElem, contract); - } - break; - case "operations": - var operationElems = Object.keys(DomElems.operations); - for (var i = 0; i < operationElems.length; ++i) { - var operationElem = DomElems.operations[operationElems[i]]; - var name = operationElem.name; - if (this.action.type === ActionTypes["Operation"] && name === this.action.name) { - operationElem.classList.add(ActiveActionCssClass); - } else { - operationElem.classList.remove(ActiveActionCssClass); - } - var operation = this.operations[name]; - if (operation == null) { - throw new Error("Could not find Operation " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateOperationsUIElement(operationElem, operation); - } - break; - case "blackops": - var blackopsElems = Object.keys(DomElems.blackops); - for (var i = 0; i < blackopsElems.length; ++i) { - var blackopElem = DomElems.blackops[blackopsElems[i]]; - var name = blackopElem.name; - if (this.action.type === ActionTypes["BlackOperation"] && name === this.action.name) { - blackopElem.classList.add(ActiveActionCssClass); - } else { - blackopElem.classList.remove(ActiveActionCssClass); - } - var blackop = BlackOperations[name]; - if (blackop == null) { - throw new Error("Could not find BlackOperation " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateBlackOpsUIElement(blackopElem, blackop); - } - break; - case "skills": - var skillElems = Object.keys(DomElems.skills); - for (var i = 0; i < skillElems.length; ++i) { - var skillElem = DomElems.skills[skillElems[i]]; - var name = skillElem.name; - var skill = Skills[name]; - if (skill == null) { - throw new Error("Could not find Skill " + name + " in Bladeburner.updateActionAndSkillsContent()"); - } - this.updateSkillsUIElement(skillElem, skill); - } - break; - default: - throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent"); - } -} - -Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block", - })); - - if (isActive) { //Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) - })); - } else { - //Start button - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - this.action.type = ActionTypes[action.name]; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - } - - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { //Info - innerHTML:action.desc, display:"inline-block" - })); - - -} - -Bladeburner.prototype.updateContractsUIElement = function(el, action) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block" - })); - - if (isActive) { //Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) - })); - } else { //Start button - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - padding:"3px", margin:"3px", - clickListener:()=>{ - this.action.type = ActionTypes.Contract; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - } - - //Level and buttons to change level - var maxLevel = (action.level >= action.maxLevel); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { - display:"inline-block", - innerText:"Level: " + action.level + " / " + action.maxLevel - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", - display:"inline", - clickListener:()=>{ - ++action.level; - if (isActive) {this.startAction(this.action);} //Restart Action - this.updateContractsUIElement(el, action); - return false; - } - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", - display:"inline", - clickListener:()=>{ - --action.level; - if (isActive) {this.startAction(this.action);} //Restart Action - this.updateContractsUIElement(el, action); - return false; - } - })); - - var actionTime = action.getActionTime(this); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { //Info - display:"inline-block", - innerHTML:action.desc + "\n\n" + - "Estimated success chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + - "Time Required (s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 0) + "\n" + - "Contracts remaining: " + Math.floor(action.count) + "\n" + - "Successes: " + action.successes + "\n" + - "Failures: " + action.failures, - })); - - //Autolevel Checkbox - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); - var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("label", { - for:autolevelCheckboxId, innerText:"Autolevel",color:"white", - tooltip:"Automatically increase contract level when possible" - })); - var autolevelCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { - type:"checkbox", id:autolevelCheckboxId, margin:"4px", - checked:action.autoLevel, - changeListener:()=>{ - action.autoLevel = autolevelCheckbox.checked; - } - }); - el.appendChild(autolevelCheckbox); -} - -Bladeburner.prototype.updateOperationsUIElement = function(el, action) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block" - })); - - if (isActive) { //Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) - })); - } else { //Start button and set Team Size button - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Start", class: "a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - this.action.type = ActionTypes.Operation; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - var popupId = "bladeburner-operation-set-team-size-popup"; - var txt = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"Enter the amount of team members you would like to take on these " + - "operations. If you do not have the specified number of team members, " + - "then as many as possible will be used. Note that team members may " + - "be lost during operations." - - }); - var input = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { - type:"number", placeholder: "Team Members" - }); - var setBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Confirm", class:"a-link-button", - clickListener:()=>{ - var num = Math.round(parseFloat(input.value)); - if (isNaN(num)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") - } else { - action.teamCount = num; - this.updateOperationsUIElement(el, action); - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); - return false; - } - }); - var cancelBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Cancel", class:"a-link-button", - clickListener:()=>{ - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); - return false; - } - }); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); - } - })); - } - - //Level and buttons to change level - var maxLevel = (action.level >= action.maxLevel); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { - display:"inline-block", - innerText:"Level: " + action.level + " / " + action.maxLevel - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", - display:"inline", - clickListener:()=>{ - ++action.level; - if (isActive) {this.startAction(this.action);} //Restart Action - this.updateOperationsUIElement(el, action); - return false; - } - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", - padding:"2px", margin:"2px", - tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", - display:"inline", - clickListener:()=>{ - --action.level; - if (isActive) {this.startAction(this.action);} //Restart Action - this.updateOperationsUIElement(el, action); - return false; - } - })); - - //General Info - var difficulty = action.getDifficulty(); - var actionTime = action.getActionTime(this); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { - display:"inline-block", - innerHTML:action.desc + "\n\n" + - "Estimated success chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + - "Time Required(s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 1) + "\n" + - "Operations remaining: " + Math.floor(action.count) + "\n" + - "Successes: " + action.successes + "\n" + - "Failures: " + action.failures, - })); - - //Autolevel Checkbox - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); - var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("label", { - for:autolevelCheckboxId, innerText:"Autolevel",color:"white", - tooltip:"Automatically increase operation level when possible" - })); - var autolevelCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { - type:"checkbox", id:autolevelCheckboxId, margin:"4px", - checked:action.autoLevel, - changeListener:()=>{ - action.autoLevel = autolevelCheckbox.checked; - } - }); - el.appendChild(autolevelCheckbox); -} - -Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); - var isActive = el.classList.contains(ActiveActionCssClass); - var isCompleted = (this.blackops[action.name] != null); - var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); - var difficulty = action.getDifficulty(); - var actionTime = action.getActionTime(this); - var hasReqdRank = this.rank >= action.reqdRank; - - //UI for Completed Black Op - if (isCompleted) { - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { - innerText:action.name + " (COMPLETED)", display:"block", - })); - return; - } - - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header - innerText:isActive ? action.name + " (IN PROGRESS - " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" - : action.name, - display:"inline-block", - })); - - if (isActive) { //Progress bar if its active - var progress = this.actionTimeCurrent / this.actionTimeToComplete; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) - })); - } else { - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Start button - innerText:"Start", margin:"3px", padding:"3px", - class:hasReqdRank ? "a-link-button" : "a-link-button-inactive", - clickListener:()=>{ - this.action.type = ActionTypes.BlackOperation; - this.action.name = action.name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - return false; - } - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Set Team Size Button - innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", - margin:"3px", padding:"3px", - clickListener:()=>{ - var popupId = "bladeburner-operation-set-team-size-popup"; - var txt = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - innerText:"Enter the amount of team members you would like to take on this " + - "BlackOp. If you do not have the specified number of team members, " + - "then as many as possible will be used. Note that team members may " + - "be lost during operations." - - }); - var input = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { - type:"number", placeholder: "Team Members" - }); - var setBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Confirm", class:"a-link-button", - clickListener:()=>{ - var num = Math.round(parseFloat(input.value)); - if (isNaN(num)) { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") - } else { - action.teamCount = num; - this.updateBlackOpsUIElement(el, action); - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); - return false; - } - }); - var cancelBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { - innerText:"Cancel", class:"a-link-button", - clickListener:()=>{ - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); - return false; - } - }); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); - } - })); - } - - //Info - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"inline-block", - innerHTML:"
" + action.desc + "

", - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", color:hasReqdRank ? "white" : "red", - innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.reqdRank, 0) + "
" - })); - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"inline-block", - innerHTML:"Estimated Success Chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + - "Time Required(s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 1), - })) -} - -Bladeburner.prototype.updateSkillsUIElement = function(el, skill) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); - var skillName = skill.name; - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var pointCost = skill.baseCost + (currentLevel * skill.costInc); - - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header - innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block" - })); - - var canLevel = this.skillPoints >= pointCost; - var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false; - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Level up button - innerText:"Level", display:"inline-block", - class: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive", - margin:"3px", padding:"3px", - clickListener:()=>{ - this.skillPoints -= pointCost; - this.upgradeSkill(skill); - this.createActionAndSkillsContent(); - return false; - } - })); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); - if (maxLvl) { - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - color:"red", display:"block", - innerText:"MAX LEVEL" - })); - } else { - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { - display:"block", - innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(pointCost, 0), - })); - } - el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { //Info/Description - innerHTML:skill.desc, display:"inline-block", - })); -} - -//Bladeburner Console Window -Bladeburner.prototype.postToConsole = function(input) { - if (input == null || DomElems.consoleDiv == null) {return;} - $("#bladeubrner-console-input-row").before('' + input + ''); - if (DomElems.consoleTable.childNodes.length > 200) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } - this.updateConsoleScroll(); -} - -Bladeburner.prototype.updateConsoleScroll = function() { - DomElems.consoleDiv.scrollTop = DomElems.consoleDiv.scrollHeight; -} - -Bladeburner.prototype.resetConsoleInput = function() { - DomElems.consoleInput.value = ""; -} - -Bladeburner.prototype.clearConsole = function() { - while (DomElems.consoleTable.childNodes.length > 1) { - DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); - } -} - -Bladeburner.prototype.log = function(input) { - //Adds a timestamp and then just calls postToConsole - var d = new Date(); - var timestamp = d.getMonth() + "/" + d.getDay() + " " + d.getHours() + ":" + d.getMinutes(); - this.postToConsole("[" + timestamp + "] " + input); -} - -//Handles a potential series of commands (comm1; comm2; comm3;) -Bladeburner.prototype.executeConsoleCommands = function(commands) { - try { - //Console History - if (consoleHistory[consoleHistory.length-1] != commands) { - consoleHistory.push(commands); - if (consoleHistory.length > 50) { - consoleHistory.splice(0, 1); - } - } - consoleHistoryIndex = consoleHistory.length; - - var arrayOfCommands = commands.split(";"); - for (var i = 0; i < arrayOfCommands.length; ++i) { - this.executeConsoleCommand(arrayOfCommands[i]); - } - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); - } -} - -//A single command -Bladeburner.prototype.executeConsoleCommand = function(command) { - command = command.trim(); - command = command.replace(/\s\s+/g, ' '); //Replace all whitespace w/ a single space - - var args = this.parseCommandArguments(command); - if (args.length <= 0) {return;} //Log an error? - - switch(args[0].toLowerCase()) { - case "automate": - this.executeAutomateConsoleCommand(args); - break; - case "clear": - case "cls": - this.clearConsole(); - break; - case "help": - this.executeHelpConsoleCommand(args); - break; - case "log": - this.executeLogConsoleCommand(args); - break; - case "skill": - this.executeSkillConsoleCommand(args); - break; - case "start": - this.executeStartConsoleCommand(args); - break; - case "stop": - this.resetAction(); - break; - default: - this.postToConsole("Invalid console command"); - break; - } -} - -Bladeburner.prototype.parseCommandArguments = function(command) { - //Returns an array with command and its arguments in each index. - //e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo] - //The input to this fn will be trimmed and will have all whitespace replaced w/ a single space - var args = []; - var start = 0, i = 0; - while (i < command.length) { - var c = command.charAt(i); - if (c === '"') { - var endQuote = command.indexOf('"', i+1); - if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) { - args.push(command.substr(i+1, (endQuote - i - 1))); - if (endQuote === command.length-1) { - start = i = endQuote+1; - } else { - start = i = endQuote+2; //Skip the space - } - continue; - } - } else if (c === " ") { - args.push(command.substr(start, i-start)); - start = i+1; - } - ++i; - } - if (start !== i) {args.push(command.substr(start, i-start));} - console.log("Bladeburner.parseCommandArguments returned: " + args); - return args; -} - -Bladeburner.prototype.executeAutomateConsoleCommand = function(args) { - if (args.length !== 2 && args.length !== 4) { - this.postToConsole("Invalid use of 'automate' command: automate [var] [val] [hi/low]. Use 'help automate' for more info"); - return; - } - - //Enable/Disable - if (args.length === 2) { - var flag = args[1]; - if (flag.toLowerCase() === "status") { - this.postToConsole("Automation: " + (this.automateEnabled ? "enabled" : "disabled")); - if (this.automateEnabled) { - this.postToConsole("When your stamina drops to " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.automateThreshLow, 0) + - ", you will automatically switch to " + this.automateActionLow.name + - ". When your stamina recovers to " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.automateThreshHigh, 0) + ", you will automatically " + - "switch to " + this.automateActionHigh.name + "."); - } - - } else if (flag.toLowerCase().includes("en")) { - if (!(this.automateActionLow instanceof ActionIdentifier) || - !(this.automateActionHigh instanceof ActionIdentifier)) { - return this.log("Failed to enable automation. Actions were not set"); - } - this.automateEnabled = true; - this.log("Bladeburner automation enabled"); - } else if (flag.toLowerCase().includes("d")) { - this.automateEnabled = false; - this.log("Bladeburner automation disabled"); - } else { - this.log("Invalid argument for 'automate' console command: " + args[1]); - } - return; - } - - //Set variables - if (args.length === 4) { - var variable = args[1], val = args[2]; - - var highLow = false; //True for high, false for low - if (args[3].toLowerCase().includes("hi")) {highLow = true;} - - switch (variable) { - case "general": - case "gen": - if (GeneralActions[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes[val], name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid action name specified: " + val); - } - break; - case "contract": - case "contracts": - if (this.contracts[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes.Contract, name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid contract name specified: " + val); - } - break; - case "ops": - case "op": - case "operations": - case "operation": - if (this.operations[val] != null) { - var action = new ActionIdentifier({ - type:ActionTypes.Operation, name:val - }); - if (highLow) { - this.automateActionHigh = action; - } else { - this.automateActionLow = action; - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); - } else { - this.postToConsole("Invalid Operation name specified: " + val); - } - break; - case "stamina": - if (isNaN(val)) { - this.postToConsole("Invalid value specified for stamina threshold (must be numeric): " + val); - } else { - if (highLow) { - this.automateThreshHigh = Number(val); - } else { - this.automateThreshLow = Number(val); - } - this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") stamina threshold set to " + val); - } - break; - default: - break; - } - - return; - } -} - -Bladeburner.prototype.executeHelpConsoleCommand = function(args) { - if (args.length === 1) { - this.postToConsole(consoleHelpText.helpList); - } else { - for (var i = 1; i < args.length; ++i) { - var commandText = consoleHelpText[args[i]]; - if (commandText != null) { - this.postToConsole(commandText); - this.postToConsole("
"); - } - } - } -} - -Bladeburner.prototype.executeLogConsoleCommand = function(args) { - if (args.length < 3) { - this.postToConsole("Invalid usage of log command: log [enable/disable] [action/event]"); - this.postToConsole("Use 'help log' for more details and examples"); - return; - } - - var flag = true; - if (args[1].toLowerCase().includes("d")) {flag = false;} //d for disable - - switch (args[2].toLowerCase()) { - case "general": - case "gen": - this.logging.general = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for general actions"); - break; - case "contract": - case "contracts": - this.logging.contracts = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for Contracts"); - break; - case "ops": - case "op": - case "operations": - case "operation": - this.logging.ops = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for Operations"); - break; - case "blackops": - case "blackop": - case "black operations": - case "black operation": - this.logging.blackops = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for BlackOps"); - break; - case "event": - case "events": - this.logging.events = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for events"); - break; - case "all": - this.logging.general = flag; - this.logging.contracts = flag; - this.logging.ops = flag; - this.logging.blackops = flag; - this.logging.events = flag; - this.log("Logging " + (flag ? "enabled" : "disabled") + " for everything"); - break; - default: - this.postToConsole("Invalid action/event type specified: " + args[2]); - this.postToConsole("Examples of valid action/event identifiers are: [general, contracts, ops, blackops, events]"); - break; - } -} - -Bladeburner.prototype.executeSkillConsoleCommand = function(args) { - switch (args.length) { - case 1: - //Display Skill Help Command - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - break; - case 2: - if (args[1].toLowerCase() === "list") { - //List all skills and their level - this.postToConsole("Skills: "); - var skillNames = Object.keys(Skills); - for(var i = 0; i < skillNames.length; ++i) { - var skill = Skills[skillNames[i]]; - var level = 0; - if (this.skills[skill.name] != null) {level = this.skills[skill.name];} - this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(level, 0)); - } - this.postToConsole(" "); - this.postToConsole("Effects: "); - var multKeys = Object.keys(this.skillMultipliers); - for (var i = 0; i < multKeys.length; ++i) { - var mult = this.skillMultipliers[multKeys[i]]; - if (mult && mult !== 1) { - mult = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(mult, 3); - switch(multKeys[i]) { - case "successChanceAll": - this.postToConsole("Total Success Chance: x" + mult); - break; - case "successChanceStealth": - this.postToConsole("Stealth Success Chance: x" + mult); - break; - case "successChanceKill": - this.postToConsole("Retirement Success Chance: x" + mult); - break; - case "successChanceContract": - this.postToConsole("Contract Success Chance: x" + mult); - break; - case "successChanceOperation": - this.postToConsole("Operation Success Chance: x" + mult); - break; - case "successChanceEstimate": - this.postToConsole("Synthoid Data Estimate: x" + mult); - break; - case "actionTime": - this.postToConsole("Action Time: x" + mult); - break; - case "effHack": - this.postToConsole("Hacking Skill: x" + mult); - break; - case "effStr": - this.postToConsole("Strength: x" + mult); - break; - case "effDef": - this.postToConsole("Defense: x" + mult); - break; - case "effDex": - this.postToConsole("Dexterity: x" + mult); - break; - case "effAgi": - this.postToConsole("Agility: x" + mult); - break; - case "effCha": - this.postToConsole("Charisma: x" + mult); - break; - case "effInt": - this.postToConsole("Intelligence: x" + mult); - break; - case "stamina": - this.postToConsole("Stamina: x" + mult); - break; - case "weaponAbility": - //DomElems.actionsAndSkillsDesc.innerHTML += - break; - case "gunAbility": - //DomElems.actionsAndSkillsDesc.innerHTML - break; - default: - console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]); - break; - } - } - } - } else { - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - } - break; - case 3: - var skillName = args[2]; - var skill = Skills[skillName]; - if (skill == null || !(skill instanceof Skill)) { - return this.postToConsole("Invalid skill name (Note that this is case-sensitive): " + skillName); - } - if (args[1].toLowerCase() === "list") { - this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skills[skill.name]), 0); - } else if (args[1].toLowerCase() === "level") { - var currentLevel = 0; - if (this.skills[skillName] && !isNaN(this.skills[skillName])) { - currentLevel = this.skills[skillName]; - } - var pointCost = skill.baseCost + (currentLevel * skill.costInc); - if (this.skillPoints >= pointCost) { - this.skillPoints -= pointCost; - this.upgradeSkill(skill); - this.log(skill.name + " upgraded to Level " + this.skills[skillName]); - this.createActionAndSkillsContent(); - } else { - this.postToConsole("You do not have enough Skill Points to upgrade this. You need " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(pointCost, 0)); - } - - } else { - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - } - break; - default: - this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); - this.postToConsole("Use 'help skill' for more info"); - break; - } -} - -Bladeburner.prototype.executeStartConsoleCommand = function(args) { - if (args.length !== 3) { - this.postToConsole("Invalid usage of 'start' console command: start [type] [name]"); - this.postToConsole("Use 'help start' for more info"); - return; - } - var name = args[2]; - switch (args[1].toLowerCase()) { - case "general": - case "gen": - if (GeneralActions[name] != null) { - this.action.type = ActionTypes[name]; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid action name specified: " + args[2]); - } - break; - case "contract": - case "contracts": - if (this.contracts[name] != null) { - this.action.type = ActionTypes.Contract; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid contract name specified: " + args[2]); - } - break; - case "ops": - case "op": - case "operations": - case "operation": - if (this.operations[name] != null) { - this.action.type = ActionTypes.Operation; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid Operation name specified: " + args[2]); - } - break; - case "blackops": - case "blackop": - case "black operations": - case "black operation": - if (BlackOperations[name] != null) { - this.action.type = ActionTypes.BlackOperation; - this.action.name = name; - this.startAction(this.action); - this.updateActionAndSkillsContent(); - } else { - this.postToConsole("Invalid BlackOp name specified: " + args[2]); - } - break; - default: - this.postToConsole("Invalid action/event type specified: " + args[1]); - this.postToConsole("Examples of valid action/event identifiers are: [general, contract, op, blackop]"); - break; - } -} - - -Bladeburner.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Bladeburner", this); -} -Bladeburner.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Bladeburner, value.data); -} -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Bladeburner = Bladeburner; - -//This initialized Bladeburner-related data that is NOT saved/loaded -// eg: Skill Objects, BLack Operations -//Any data that is saved/loaded should go in Bladeburner object -// eg: contracts, operations -function initBladeburner() { - //Skills - Skills[SkillNames.BladesIntuition] = new Skill({ - name:SkillNames.BladesIntuition, - desc:"Each level of this skill increases your success chance " + - "for all contracts and operations by 3%", - baseCost:5, costInc:2, - successChanceAll:3 - }); - Skills[SkillNames.Reaper] = new Skill({ - name:SkillNames.Reaper, - desc:"Each level of this skill increases your " + - "effective combat stats for Bladeburner actions by 3%", - baseCost:3, costInc:2, - effStr:3, effDef:3, effDex:3, effAgi:3 - }); - Skills[SkillNames.Cloak] = new Skill({ - name:SkillNames.Cloak, - desc:"Each level of this skill increases your " + - "success chance in stealth-related contracts and operations by 5.5%", - baseCost:3, costInc:1, - successChanceStealth:5.5 - }); - - //TODO Marksman - //TODO Weapon Proficiency - - Skills[SkillNames.Overclock] = new Skill({ - name:SkillNames.Overclock, - desc:"Each level of this skill decreases the time it takes " + - "to attempt a contract or operation by 1% (Max Level: 95)", - baseCost:5, costInc:1, maxLvl:95, - actionTime:1 - }); - Skills[SkillNames.EvasiveSystem] = new Skill({ - name:SkillNames.EvasiveSystem, - desc:"Each level of this skill increases your effective " + - "dexterity and agility for Bladeburner actions by 5%", - baseCost:2, costInc: 1, - effDex:5, effAgi:5 - }); - Skills[SkillNames.ShortCircuit] = new Skill({ - name:SkillNames.ShortCircuit, - desc:"Each level of this skill increases your success chance " + - "in contracts and operations that involve retirement by 5.5%", - baseCost:3, costInc:2, - successChanceKill:5.5 - }); - Skills[SkillNames.DigitalObserver] = new Skill({ - name:SkillNames.DigitalObserver, - desc:"Each level of this skill increases your success chance in " + - "all operations by 4%", - baseCost:5, costInc:2, - successChanceOperation:4 - }); - Skills[SkillNames.Datamancer] = new Skill({ - name:SkillNames.Datamancer, - desc:"Each level of this skill increases your effectiveness in " + - "synthoid population analysis and investigation by 5%. " + - "This affects all actions that can potentially increase " + - "the accuracy of your synthoid population/community estimates.", - baseCost:3,costInc:1, - successChanceEstimate:5 - }); - Skills[SkillNames.Tracer] = new Skill({ - name:SkillNames.Tracer, - desc:"Each level of this skill increases your success chance in " + - "all contracts by 4%", - baseCost:3, costInc:2, - successChanceContract:4 - }); - Skills[SkillNames.CybersEdge] = new Skill({ - name:SkillNames.CybersEdge, - desc:"Each level of this skill increases your max " + - "stamina by 2%", - baseCost:1, costInc:3, - stamina:2 - }); - - //General Actions - var actionName = "Training"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Improve your abilities at the Bladeburner unit's specialized training " + - "center. Doing this gives experience for all combat stats and also " + - "increases your max stamina." - }); - - var actionName = "Field Analysis"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Mine and analyze Synthoid-related data. This improve the " + - "Bladeburner's unit intelligence on Synthoid locations and " + - "activities. Completing this action will improve the accuracy " + - "of your Synthoid population estimated in the current city.

" + - "Does NOT require stamina." - }); - - var actionName = "Recruitment"; - GeneralActions[actionName] = new Action({ - name:actionName, - desc:"Attempt to recruit members for your Bladeburner team. These members " + - "can help you conduct operations.

" + - "Does NOT require stamina." - }); - - //Black Operations - BlackOperations["Operation Typhoon"] = new BlackOperation({ - name:"Operation Typhoon", - desc:"Obadiah Zenyatta is the leader of a RedWater PMC. It has long " + - "been known among the intelligence community that Zenyatta, along " + - "with the rest of the PMC, is a Synthoid.

" + - "The goal of Operation Typhoon is to find and eliminate " + - "Zenyatta and RedWater by any means necessary. After the task " + - "is completed, the actions must be covered up from the general public.", - baseDifficulty:2000, reqdRank:2.5e3, - rankGain:25, rankLoss:10, hpLoss:100, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Zero"] = new BlackOperation({ - name:"Operation Zero", - desc:"AeroCorp is one of the world's largest defense contractors. " + - "It's leader, Steve Watataki, is thought to be a supporter of " + - "Synthoid rights. He must be removed.

" + - "The goal of Operation Zero is to covertly infiltrate AeroCorp and " + - "uncover any incriminating evidence or " + - "information against Watataki that will cause him to be removed " + - "from his position at AeroCorp. Incriminating evidence can be " + - "fabricated as a last resort. Be warned that AeroCorp has some of " + - "the most advanced security measures in the world.", - baseDifficulty:2500, reqdRank:5e3, - rankGain:30, rankLoss:15, hpLoss:50, - weights:{hack:0.2,str:0.15,def:0.15,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isStealth:true - }); - BlackOperations["Operation X"] = new BlackOperation({ - name:"Operation X", - desc:"We have recently discovered an underground publication " + - "group called Samizdat. Even though most of their publications " + - "are nonsensical conspiracy theories, the average human is " + - "gullible enough to believe them. Many of their works discuss " + - "Synthoids and pose a threat to society. The publications are spreading " + - "rapidly in China and other Eastern countries.

" + - "Samizdat has done a good job of keeping hidden and anonymous. " + - "However, we've just received intelligence that their base of " + - "operations is in Ishima's underground sewer systems. Your task is to " + - "investigate the sewer systems, and eliminate Samizdat. They must " + - "never publish anything again.", - baseDifficulty:3000, reqdRank:7.5e3, - rankGain:30, rankLoss:15, hpLoss:100, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Titan"] = new BlackOperation({ - name:"Operation Titan", - desc:"Several months ago Titan Laboratories' Bioengineering department " + - "was infiltrated by Synthoids. As far as we know, Titan Laboratories' " + - "management has no knowledge about this. We don't know what the " + - "Synthoids are up to, but the research that they could " + - "be conducting using Titan Laboraties' vast resources is potentially " + - "very dangerous.

" + - "Your goal is to enter and destroy the Bioengineering department's " + - "facility in Aevum. The task is not just to retire the Synthoids there, but " + - "also to destroy any information or research at the facility that " + - "is relevant to the Synthoids and their goals.", - baseDifficulty:4000, reqdRank:10e3, - rankGain:40, rankLoss:20, hpLoss:100, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Ares"] = new BlackOperation({ - name:"Operation Ares", - desc:"One of our undercover agents, Agent Carter, has informed us of a " + - "massive weapons deal going down in Dubai between rogue Russian " + - "militants and a radical Synthoid community. These weapons are next-gen " + - "plasma and energy weapons. It is critical for the safety of humanity " + - "that this deal does not happen.

" + - "Your task is to intercept the deal. Leave no survivors.", - baseDifficulty:5000, reqdRank:12.5e3, - rankGain:40, rankLoss:20, hpLoss:200, - weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0}, - decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Archangel"] = new BlackOperation({ - name:"Operation Archangel", - desc:"Our analysts have discovered that the popular Red Rabbit brothel in " + - "Amsterdam is run and 'staffed' by MK-VI Synthoids. Intelligence " + - "suggests that the profit from this brothel is used to fund a large " + - "black market arms trafficking operation.

" + - "The goal of this operation is to take out the leaders that are running " + - "the Red Rabbit brothel. Try to limit the number of other casualties, " + - "but do what you must to complete the mission.", - baseDifficulty:7500, reqdRank:15e3, - rankGain:50, rankLoss:20, hpLoss:25, - weights:{hack:0,str:0.2,def:0.2,dex:0.3,agi:0.3,cha:0, int:0}, - decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true, - }); - BlackOperations["Operation Juggernaut"] = new BlackOperation({ - name:"Operation Juggernaut", - desc:"The CIA has just encountered a new security threat. A new " + - "criminal group, lead by a shadowy operative who calls himself " + - "Juggernaut, has been smuggling drugs and weapons (including " + - "suspected bioweapons) into Sector-12. We also have reason " + - "to believe the tried to break into one of Universal Energy's " + - "facilities in order to cause a city-wide blackout. The CIA " + - "suspects that Juggernaut is a heavily-augmented Synthoid, and " + - "have thus enlisted our help.

" + - "Your mission is to eradicate Juggernaut and his followers.", - baseDifficulty:10e3, reqdRank:20e3, - rankGain:75, rankLoss:40, hpLoss:300, - weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0}, - decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true, - }); - BlackOperations["Operation Red Dragon"] = new BlackOperation({ - name:"Operation Red Dragon", - desc:"The Tetrads criminal organization is suspected of " + - "reverse-engineering the MK-VI Synthoid design. We believe " + - "they altered and possibly improved the design and began " + - "manufacturing their own Synthoid models in order to bolster " + - "their criminal activities.

" + - "Your task is to infiltrate and destroy the Tetrads' base of operations " + - "in Los Angeles. Intelligence tells us that their base houses " + - "one of their Synthoid manufacturing units.", - baseDifficulty:12.5e3, reqdRank:25e3, - rankGain:100, rankLoss:50, hpLoss:500, - weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true, - }); - BlackOperations["Operation K"] = new BlackOperation({ - name:"Operation K", - desc:"CODE RED SITUATION. Our intelligence tells us that VitaLife " + - "has discovered a new android cloning technology. This technology " + - "is supposedly capable of cloning Synthoid, not only physically " + - "but also their advanced AI modules. We do not believe that " + - "VitaLife is trying to use this technology illegally or " + - "maliciously, but if any Synthoids were able to infiltrate the " + - "corporation and take advantage of this technology then the " + - "results would be catastrophic.

" + - "We do not have the power or jurisdiction to shutdown this down " + - "through legal or political means, so we must resort to a covert " + - "operation. Your goal is to destroy this technology and eliminate" + - "anyone who was involved in its creation.", - baseDifficulty:15e3, reqdRank:30e3, - rankGain:120, rankLoss:60, hpLoss:1000, - weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Deckard"] = new BlackOperation({ - name:"Operation Deckard", - desc:"Despite your success in eliminating VitaLife's new android-replicating " + - "technology in Operation K, we've discovered that a small group of " + - "MK-VI Synthoids were able to make off with the schematics and design " + - "of the technology before the Operation. It is almost a certainty that " + - "these Synthoids are some of the rogue MK-VI ones from the Synthoid Uprising." + - "The goal of Operation Deckard is to hunt down these Synthoids and retire " + - "them. I don't need to tell you how critical this mission is.", - baseDifficulty:20e3, reqdRank:40e3, - rankGain:150, rankLoss:75, hpLoss:200, - weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, - decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true, - }); - BlackOperations["Operation Tyrell"] = new BlackOperation({ - name:"Operation Tyrell", - desc:"A week ago Blade Industries reported a small break-in at one " + - "of their Aevum Augmentation storage facitilities. We figured out " + - "that The Dark Army was behind the heist, and didn't think any more " + - "of it. However, we've just discovered that several known MK-VI Synthoids " + - "were part of that break-in group.

" + - "We cannot have Synthoids upgrading their already-enhanced abilities " + - "with Augmentations. Your task is to hunt down the associated Dark Army " + - "members and eliminate them.", - baseDifficulty:25e3, reqdRank:50e3, - rankGain:200, rankLoss:100, hpLoss:500, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true, - }); - BlackOperations["Operation Wallace"] = new BlackOperation({ - name:"Operation Wallace", - desc:"Based on information gathered from Operation Tyrell, we've discovered " + - "that The Dark Army was well aware that there were Synthoids amongst " + - "their ranks. Even worse, we believe that The Dark Army is working " + - "together with other criminal organizations such as The Syndicate and " + - "that they are planning some sort of large-scale takeover of multiple major " + - "cities, most notably Aevum. We suspect that Synthoids have infiltrated " + - "the ranks of these criminal factions and are trying to stage another " + - "Synthoid uprising.

" + - "The best way to deal with this is to prevent it before it even happens. " + - "The goal of Operation Wallace is to destroy the Dark Army and " + - "Syndicate factions in Aevum immediately. Leave no survivors.", - baseDifficulty:30e3, reqdRank:75e3, - rankGain:500, rankLoss:150, hpLoss:1500, - weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Shoulder of Orion"] = new BlackOperation({ - name:"Operation Shoulder of Orion", - desc:"China's Solaris Space Systems is secretly launching the first " + - "manned spacecraft in over a decade using Synthoids. We believe " + - "China is trying to establish the first off-world colonies.

" + - "The mission is to prevent this launch without instigating an " + - "international conflict. When you accept this mission you will be " + - "officially disavowed by the NSA and the national government until after you " + - "successfully return. In the event of failure, all of the operation's " + - "team members must not let themselves be captured alive.", - baseDifficulty:35e3, reqdRank:100e3, - rankGain:1e3, rankLoss:500, hpLoss:1500, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isStealth:true - }); - BlackOperations["Operation Hyron"] = new BlackOperation({ - name:"Operation Hyron", - desc:"Our intelligence tells us that Fulcrum Technologies is developing " + - "a quantum supercomputer using human brains as core " + - "processors. This supercomputer " + - "is rumored to be able to store vast amounts of data and " + - "perform computations unmatched by any other supercomputer on the " + - "planet. But more importantly, the use of organic human brains " + - "means that the supercomputer may be able to reason abstractly " + - "and become self-aware.

" + - "I do not need to remind you why sentient-level AIs pose a serious " + - "thread to all of mankind.

" + - "The research for this project is being conducted at one of Fulcrum " + - "Technologies secret facilities in Aevum, codenamed 'Alpha Ranch'. " + - "Infiltrate the compound, delete and destroy the work, and then find and kill the " + - "project lead.", - baseDifficulty:40e3, reqdRank:125e3, - rankGain:2e3, rankLoss:1e3, hpLoss:500, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Morpheus"] = new BlackOperation({ - name:"Operation Morpheus", - desc:"DreamSense Technologies is an advertising company that uses " + - "special technology to transmit their ads into the peoples " + - "dreams and subconcious. They do this using broadcast transmitter " + - "towers. Based on information from our agents and informants in " + - "Chonqging, we have reason to believe that one of the broadcast " + - "towers there has been compromised by Synthoids and is being used " + - "to spread pro-Synthoid propaganda.

" + - "The mission is to destroy this broadcast tower. Speed and " + - "stealth are of the upmost important for this.", - baseDifficulty:45e3, reqdRank:150e3, - rankGain:5e3, rankLoss:1e3, hpLoss:100, - weights:{hack:0.05,str:0.15,def:0.15,dex:0.3,agi:0.3,cha:0, int:0.05}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isStealth:true - }); - BlackOperations["Operation Ion Storm"] = new BlackOperation({ - name:"Operation Ion Storm", - desc:"Our analysts have uncovered a gathering of MK-VI Synthoids " + - "that have taken up residence in the Sector-12 Slums. We " + - "don't know if they are rogue Synthoids from the Uprising, " + - "but we do know that they have been stockpiling " + - "weapons, money, and other resources. This makes them dangerous.

" + - "This is a full-scale assault operation to find and retire all of these " + - "Synthoids in the Sector-12 Slums.", - baseDifficulty:50e3, reqdRank:175e3, - rankGain:5e3, rankLoss:1e3, hpLoss:5000, - weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Annihilus"] = new BlackOperation({ - name:"Operation Annihilus", - desc:"Our superiors have ordered us to eradicate everything and everyone " + - "in an underground facility located in Aevum. They tell us " + - "that the facility houses many dangerous Synthoids and " + - "belongs to a terrorist organization called " + - "'The Covenant'. We have no prior intelligence about this " + - "organization, so you are going in blind.", - baseDifficulty:55e3, reqdRank:200e3, - rankGain:5e3, rankLoss:1e3, hpLoss:10e3, - weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Ultron"] = new BlackOperation({ - name:"Operation Ultron", - desc:"OmniTek Incorporated, the original designer and manufacturer of Synthoids, " + - "has notified us of a malfunction in their AI design. This malfunction, " + - "when triggered, causes MK-VI Synthoids to become radicalized and seek out " + - "the destruction of humanity. They say that this bug affects all MK-VI Synthoids, " + - "not just the rogue ones from the Uprising.

" + - "OmniTek has also told us they they believe someone has triggered this " + - "malfunction in a large group of MK-VI Synthoids, and that these newly-radicalized Synthoids " + - "are now amassing in Volhaven to form a terrorist group called Ultron.

" + - "Intelligence suggests Ultron is heavily armed and that their members are " + - "augmented. We believe Ultron is making moves to take control of " + - "and weaponize DeltaOne's Tactical High-Energy Satellite Laser Array (THESLA).

" + - "Your task is to find and destroy Ultron.", - baseDifficulty:60e3, reqdRank:250e3, - rankGain:10e3, rankLoss:2e3, hpLoss:10e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - isKill:true - }); - BlackOperations["Operation Centurion"] = new BlackOperation({ - name:"Operation Centurion", - desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)

" + - "Throughout all of humanity's history, we have relied on " + - "technology to survive, conquer, and progress. Its advancement became our primary goal. " + - "And at the peak of human civilization technology turned into " + - "power. Global, absolute power.

" + - "It seems that the universe is not without a sense of irony.

" + - "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", - baseDifficulty:70e3, reqdRank:300e3, - rankGain:15e3, rankLoss:5e3, hpLoss:10e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - }); - BlackOperations["Operation Vindictus"] = new BlackOperation({ - name:"Operation Vindictus", - desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)

" + - "The bits are all around us. The daemons that hold the Node " + - "together can manifest themselves in many different ways.

" + - "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", - baseDifficulty:75e3, reqdRank:350e3, - rankGain:20e3, rankLoss:20e3, hpLoss:20e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - }); - BlackOperations["Operation Daedalus"] = new BlackOperation({ - name:"Operation Daedalus", - desc:"Yesterday we obeyed kings and bent our neck to emperors. " + - "Today we kneel only to truth.", - baseDifficulty:80e3, reqdRank:400e3, - rankGain:40e3, rankLoss:10e3, hpLoss:100e3, - weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, - decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, - }); -} - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) - -/***/ }), -/* 28 */ -/*!****************************!*\ - !*** ./src/FactionInfo.js ***! - \****************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FactionInfo", function() { return FactionInfo; }); -//Contains the "information" property for all the Factions, which is just a description -//of each faction -let FactionInfo = { - //Endgame - IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " + - "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", - - DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", - - CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " + - "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.

" + - "Only then can you discover immortality.", - - //Megacorporations, each forms its own faction - ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " + - "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " + - "information universally accessible.", - - MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " + - "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " + - "transporation on an unprecendented scale, in ways that no other company can.

" + - "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.", - - BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are.

" + - "Legal Insight - Business Instinct - Experience Innovation", - - BladeIndustriesInfo: "Augmentation is salvation", - - NWOInfo: "The human being does not truly desire freedom. It wants " + - "to be observed, understood, and judged. It wants to be given purpose and " + - "direction in its life. That is why humans created God. " + - "And that is why humans created civilization - " + - "not because of willingness, " + - "but because of a need to be incorporated into higher orders of structure and meaning.", - - ClarkeIncorporatedInfo: "Unlocking the power of the genome", - - OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference", - - FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " + - "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", - - KuaiGongInternationalInfo: "Dream big. Work hard. Make history.", - - //Other Corporations - FulcrumSecretTechnologiesInfo: "The human organism has an innate desire to worship. " + - "That is why they created gods. If there were no gods, " + - "it would be necessary to create them. And now we can.", - - //Hacker groups - BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+ - "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " + - "to move, to live, to operate at any level without the use of bits. " + - "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " + - "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.

" + - "Those who run the bits, run the world", - - - BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " + - "Technological power. " + - "And those at the top rule with an invisible hand. They built a society where the rich get richer, " + - "and everyone else suffers.

" + - "So much pain. So many lives. Their darkness must end.", - - NiteSecInfo: -" __..__
" + -" _.nITESECNIt.
" + -" .-'NITESECNITESEc.
" + -" .' NITESECNITESECn
" + -" / NITESECNITESEC;
" + -" : :NITESECNITESEC;
" + -" ; $ NITESECNITESECN
" + -" : _, ,N'ITESECNITESEC
" + -" : .+^^`, : `NITESECNIT
" + -" ) /), `-,-=,NITESECNI
" + -" / ^ ,-;|NITESECN;
" + -" / _.' '-';NITESECN
" + -" ( , ,-''`^NITE'
" + -" )` :`. .'
" + -" )-- ; `- /
" + -" \' _.-' :
" + -" ( _.-' \. \
" + -" \------. \ \
" + -" \. \ \
" + -" \ _.nIt
" + -" \ _.nITESECNi
" + -" nITESECNIT^' \
" + -" NITE^' ___ \
" + -" / .gP''''Tp. \
" + -" : d' . `b \
" + -" ; d' o `b ;
" + -" / d; `b|
" + -" /, $; @ `:
" + -" /' $$ ;
" + -" .' $$b o |
" + -" .' d$$$; :
" + -" / .d$$$$; , ;
" + -" d .dNITESEC $ |
" + -" :bp.__.gNITESEC$$ :$ ;
" + -" NITESECNITESECNIT $$b :
", - - //City factions, essentially governments - ChongqingInfo: "Serve the people", - Sector12Info: "The City of the Future", - HongKongInfo: "Asia's World City", - AevumInfo: "The Silicon City", - IshimaInfo: "The East Asian Order of the Future", - VolhavenInfo: "Benefit, Honour, and Glory", - - //Criminal Organizations/Gangs - SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.", - - DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.", - - TheSyndicateInfo: "Honor holds you back", - - SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " + - "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " + - "for.\n\n" + - "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.", - - TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way", - - SlumSnakesInfo: "Slum Snakes rule!", - - //Earlygame factions - factions the player will prestige with early on that don't - //belong in other categories - NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~", - - TianDiHuiInfo: "Obey Heaven and Work Righteousness", - - CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesn’t understand, " + - "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " + - "dominated by the internet, society approaches the brink of total chaos. " + - "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.", - - //Special Factions - BladeburnersInfo: "It's too bad they won't live. But then again, who does?

" + - "Note that for this faction, reputation can only be gained through Bladeburner actions. Completing " + - "Bladeburner contracts/operations will increase your reputation.", -} - - - - -/***/ }), -/* 29 */ /*!************************!*\ !*** ./src/Message.js ***! \************************/ @@ -29906,15 +26944,15 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadMessages", function() { return loadMessages; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMessages", function() { return initMessages; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Message", function() { return Message; }); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions.js */ 34); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions.js */ 39); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./RedPill.js */ 45); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./RedPill.js */ 41); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); @@ -30109,3991 +27147,7 @@ function initMessages() { /***/ }), -/* 30 */ -/*!**********************!*\ - !*** ./src/Alias.js ***! - \**********************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Aliases", function() { return Aliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlobalAliases", function() { return GlobalAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printAliases", function() { return printAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseAliasDeclaration", function() { return parseAliasDeclaration; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeAlias", function() { return removeAlias; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "substituteAliases", function() { return substituteAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAliases", function() { return loadAliases; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGlobalAliases", function() { return loadGlobalAliases; }); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Terminal.js */ 18); - - -let Aliases = {}; -let GlobalAliases = {}; - -function loadAliases(saveString) { - if (saveString === "") { - Aliases = {}; - } else { - Aliases = JSON.parse(saveString); - } -} - -function loadGlobalAliases(saveString) { - if (saveString === "") { - GlobalAliases = {}; - } else { - GlobalAliases = JSON.parse(saveString); - } -} - -//Print all aliases to terminal -function printAliases() { - for (var name in Aliases) { - if (Aliases.hasOwnProperty(name)) { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_0__["post"])("alias " + name + "=" + Aliases[name]); - } - } - for (var name in GlobalAliases) { - if (GlobalAliases.hasOwnProperty(name)) { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_0__["post"])("global alias " + name + "=" + GlobalAliases[name]); - } - } -} - -//True if successful, false otherwise -function parseAliasDeclaration(dec,global=false) { - var re = /^([_|\w|!|%|,|@]+)="(.+)"$/; - var matches = dec.match(re); - if (matches == null || matches.length != 3) {return false;} - if (global){ - addGlobalAlias(matches[1],matches[2]); - } else { - addAlias(matches[1], matches[2]); - } - return true; -} - -function addAlias(name, value) { - if (name in GlobalAliases){ - delete GlobalAliases[name]; - } - Aliases[name] = value; -} - -function addGlobalAlias(name, value) { - if (name in Aliases){ - delete Aliases[name]; - } - GlobalAliases[name] = value; -} - -function getAlias(name) { - if (Aliases.hasOwnProperty(name)) { - return Aliases[name]; - } - return null; -} - -function getGlobalAlias(name) { - if (GlobalAliases.hasOwnProperty(name)) { - return GlobalAliases[name]; - } - return null; -} - -function removeAlias(name) { - if (Aliases.hasOwnProperty(name)) { - delete Aliases[name]; - return true; - } - if (GlobalAliases.hasOwnProperty(name)) { - delete GlobalAliases[name]; - return true; - } - return false; -} - -//Returns the original string with any aliases substituted in -//Aliases only applied to "whole words", one level deep -function substituteAliases(origCommand) { - var commandArray = origCommand.split(" "); - if (commandArray.length>0){ - var alias = getAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } else { - var alias = getGlobalAlias(commandArray[0]); - if (alias != null) { - commandArray[0] = alias; - } - } - for (var i = 0; i < commandArray.length; ++i) { - var alias = getGlobalAlias(commandArray[i]); - if (alias != null) { - commandArray[i] = alias; - } - } - } - return commandArray.join(" "); -} - - - - -/***/ }), -/* 31 */ -/*!***********************************!*\ - !*** ./src/NetscriptFunctions.js ***! - \***********************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptFunctions", function() { return NetscriptFunctions; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSingularitySFFlags", function() { return initSingularitySFFlags; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasSingularitySF", function() { return hasSingularitySF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBn11SF", function() { return hasBn11SF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasWallStreetSF", function() { return hasWallStreetSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wallStreetSFLvl", function() { return wallStreetSFLvl; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasCorporationSF", function() { return hasCorporationSF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasAISF", function() { return hasAISF; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasBladeburnerSF", function() { return hasBladeburnerSF; }); -/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 41); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Crimes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Crimes.js */ 20); -/* harmony import */ var _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Bladeburner.js */ 27); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Company.js */ 9); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./DarkWeb.js */ 35); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./HacknetNode.js */ 40); -/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Message.js */ 29); -/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Missions.js */ 34); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./StockMarket.js */ 22); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var _TextFile_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./TextFile.js */ 43); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); -/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 6); -/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 69); -/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./NetscriptPort.js */ 46); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! decimal.js */ 24); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); -var sprintf = __webpack_require__(/*! sprintf-js */ 68).sprintf, - vsprintf = __webpack_require__(/*! sprintf-js */ 68).vsprintf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -var hasCorporationSF = false, //Source-File 3 - hasSingularitySF = false, //Source-File 4 - hasAISF = false, //Source-File 5 - hasBladeburnerSF = false, //Source-File 6 - hasBladeburner2079SF = false, //Source-File 7 - hasWallStreetSF = false, //Source-File 8 - hasBn11SF = false; //Source-File 11 - -var singularitySFLvl=1, wallStreetSFLvl=1; - -var possibleLogs = { - ALL: true, - scan: true, - hack: true, - sleep: true, - disableLog: true, - enableLog: true, - grow: true, - weaken: true, - nuke: true, - brutessh: true, - ftpcrack: true, - relaysmtp: true, - httpworm: true, - sqlinject: true, - spawn: true, - kill: true, - killall: true, - scp: true, - getHackingLevel: true, - getServerMoneyAvailable: true, - getServerSecurityLevel: true, - getServerBaseSecurityLevel: true, - getServerMinSecurityLevel: true, - getServerRequiredHackingLevel: true, - getServerMaxMoney: true, - getServerGrowth: true, - getServerNumPortsRequired: true, - getServerRam: true, - buyStock: true, - sellStock: true, - purchaseServer: true, - deleteServer: true, - universityCourse: true, - gymWorkout: true, - travelToCity: true, - purchaseTor: true, - purchaseProgram: true, - stopAction: true, - upgradeHomeRam: true, - workForCompany: true, - applyToCompany: true, - joinFaction: true, - workForFaction: true, - createProgram: true, - commitCrime: true, - shortStock: true, - sellShort: true, -} - -//Used to check and set flags for every Source File, despite the name of the function -function initSingularitySFFlags() { - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles.length; ++i) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 3) {hasCorporationSF = true;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 4) { - hasSingularitySF = true; - singularitySFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].lvl; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 5) {hasAISF = true;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 8) { - hasWallStreetSF = true; - wallStreetSFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].lvl; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].sourceFiles[i].n === 11) {hasBn11SF = true;} - } -} - -function NetscriptFunctions(workerScript) { - return { - Math : Math, - Date : Date, - Number : Number, - hacknetnodes : _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknetNodeWrappers, - sprintf : sprintf, - vsprintf: vsprintf, - scan : function(ip=workerScript.serverIp, hostnames=true){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.scan) { - return 0; - } else { - workerScript.loadedFns.scan = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, 'Invalid IP or hostname passed into scan() command'); - } - var out = []; - for (var i = 0; i < server.serversOnNetwork.length; i++) { - var entry; - if (hostnames) { - entry = server.getServerOnNetwork(i).hostname; - } else { - entry = server.getServerOnNetwork(i).ip; - } - if (entry == null) { - continue; - } - out.push(entry); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scan == null) { - workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname); - } - return out; - }, - hack : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.hack) { - return 0; - } else { - workerScript.loadedFns.hack = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHackRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Hack() call has incorrect number of arguments. Takes 1 argument"); - } - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping..."); - } - - //Calculate the hacking time - var hackingTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingTime"])(server); //This is in seconds - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access"); - } - - if (server.requiredHackingSkill > _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill) { - workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough"); - } - - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(hackingTime* 1000, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - var hackChance = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingChance"])(server); - var rand = Math.random(); - var expGainedOnSuccess = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; - var expGainedOnFailure = (expGainedOnSuccess / 4); - if (rand < hackChance) { //Success! - var moneyGained = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculatePercentMoneyHacked"])(server); - moneyGained = Math.floor(server.moneyAvailable * moneyGained) * threads; - - //Over-the-top safety checks - if (moneyGained <= 0) { - moneyGained = 0; - expGainedOnSuccess = expGainedOnFailure; - } - if (moneyGained > server.moneyAvailable) {moneyGained = server.moneyAvailable;} - server.moneyAvailable -= moneyGained; - if (server.moneyAvailable < 0) {server.moneyAvailable = 0;} - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainMoney(moneyGained); - workerScript.scriptRef.onlineMoneyMade += moneyGained; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug += moneyGained; - workerScript.scriptRef.recordHack(server.ip, moneyGained, threads); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGainedOnSuccess); - workerScript.scriptRef.onlineExpGained += expGainedOnSuccess; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")"); - } - server.fortify(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerFortifyAmount * threads); - return Promise.resolve(moneyGained); - } else { - //Player only gains 25% exp for failure? - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGainedOnFailure); - workerScript.scriptRef.onlineExpGained += expGainedOnFailure; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.hack == null) { - workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGainedOnFailure, 4) + " exp (t=" + threads + ")"); - } - return Promise.resolve(0); - } - }); - }, - sleep : function(time){ - if (workerScript.checkingRam) {return 0;} - if (time === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument"); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sleep == null) { - workerScript.scriptRef.log("Sleeping for " + time + " milliseconds"); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(time, workerScript).then(function() { - return Promise.resolve(true); - }); - }, - grow : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.grow) { - return 0; - } else { - workerScript.loadedFns.grow = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGrowRamCost; - } - } - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot grow this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access"); - } - - var growTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateGrowTime"])(server); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { - workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(growTime/1000, 3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(growTime, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - server.moneyAvailable += (1 * threads); //It can be grown even if it has no money - var growthPercentage = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["processSingleServerGrowth"])(server, 450 * threads); - workerScript.scriptRef.recordGrow(server.ip, threads); - var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; - if (growthPercentage == 1) { - expGain = 0; - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) { - workerScript.scriptRef.log("Available money on " + server.hostname + " grown by " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(growthPercentage*100 - 100, 6) + "%. Gained " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")"); - } - workerScript.scriptRef.onlineExpGained += expGain; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGain); - return Promise.resolve(growthPercentage); - }); - }, - weaken : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.weaken) { - return 0; - } else { - workerScript.loadedFns.weaken = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptWeakenRamCost; - } - } - var threads = workerScript.scriptRef.threads; - if (isNaN(threads) || threads < 1) {threads = 1;} - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken(). Invalid IP or hostname passed in: " + ip); - } - - //No root access or skill level too low - if (server.hasAdminRights == false) { - workerScript.scriptRef.log("Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access"); - } - - var weakenTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateWeakenTime"])(server); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { - workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(weakenTime/1000, 3) + " seconds (t=" + threads + ")"); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["netscriptDelay"])(weakenTime, workerScript).then(function() { - if (workerScript.env.stopFlag) {return Promise.reject(workerScript);} - server.weaken(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerWeakenAmount * threads); - workerScript.scriptRef.recordWeaken(server.ip, threads); - var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateExpGain"])(server) * threads; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) { - workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty + - ". Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")"); - } - workerScript.scriptRef.onlineExpGained += expGain; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainHackingExp(expGain); - return Promise.resolve(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ServerWeakenAmount * threads); - }); - }, - print : function(args){ - if (workerScript.checkingRam) {return 0;} - if (args === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument"); - } - workerScript.scriptRef.log(args.toString()); - }, - tprint : function(args) { - if (workerScript.checkingRam) {return 0;} - if (args === undefined || args == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument"); - } - var x = args.toString(); - if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isHTML"])(x)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].takeDamage(1); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_28__["dialogBoxCreate"])("You suddenly feel a sharp shooting pain through your body as an angry voice in your head exclaims:

" + - "DON'T USE TPRINT() TO OUTPUT HTML ELEMENTS TO YOUR TERMINAL!!!!

" + - "(You lost 1 HP)"); - return; - } - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_21__["post"])(workerScript.scriptRef.filename + ": " + args.toString()); - }, - clearLog : function() { - if (workerScript.checkingRam) {return 0;} - workerScript.scriptRef.clearLog(); - }, - disableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to disableLog: "+fn); - } - workerScript.disableLogs[fn] = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.disableLog == null) { - workerScript.scriptRef.log("Disabled logging for " + fn); - } - }, - enableLog : function(fn) { - if (workerScript.checkingRam) {return 0;} - if(possibleLogs[fn]===undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument to enableLog: "+fn); - } - delete workerScript.disableLogs[fn]; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.enableLog == null) { - workerScript.scriptRef.log("Enabled logging for " + fn); - } - }, - nuke : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.nuke) { - return 0; - } else { - workerScript.loadedFns.nuke = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the NUKE.exe virus!"); - } - if (server.openPortCount < server.numOpenPortsRequired) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Not enough ports opened to use NUKE.exe virus"); - } - if (server.hasAdminRights) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Already have root access to " + server.hostname); - } - } else { - server.hasAdminRights = true; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.nuke == null) { - workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access"); - } - } - return true; - }, - brutessh : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.brutessh) { - return 0; - } else { - workerScript.loadedFns.brutessh = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram)) { - workerScript.scriptRef.log("You do not have the BruteSSH.exe program!"); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the BruteSSH.exe program!"); - } - if (!server.sshPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)"); - } - server.sshPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.brutessh == null) { - workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname); - } - } - return true; - }, - ftpcrack : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.ftpcrack) { - return 0; - } else { - workerScript.loadedFns.ftpcrack = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the FTPCrack.exe program!"); - } - if (!server.ftpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)"); - } - server.ftpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.ftpcrack == null) { - workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname); - } - } - return true; - }, - relaysmtp : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.relaysmtp) { - return 0; - } else { - workerScript.loadedFns.relaysmtp = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the relaySMTP.exe program!"); - } - if (!server.smtpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)"); - } - server.smtpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.relaysmtp == null) { - workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname); - } - } - return true; - }, - httpworm : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.httpworm) { - return 0; - } else { - workerScript.loadedFns.httpworm = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the HTTPWorm.exe program!"); - } - if (!server.httpPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)"); - } - server.httpPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.httpworm == null) { - workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname); - } - } - return true; - }, - sqlinject : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.sqlinject) { - return 0; - } else { - workerScript.loadedFns.sqlinject = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPortProgramRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip); - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You do not have the SQLInject.exe program!"); - } - if (!server.sqlPortOpen) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)"); - } - server.sqlPortOpen = true; - ++server.openPortCount; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sqlinject == null) { - workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname); - } - } - return true; - }, - run : function(scriptname,threads = 1){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.run) { - return 0; - } else { - workerScript.loadedFns.run = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptRunRamCost; - } - } - if (scriptname === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into run(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads); - }, - exec : function(scriptname,ip,threads = 1) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.exec) { - return 0; - } else { - workerScript.loadedFns.exec = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptExecRamCost; - } - } - if (scriptname === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)"); - } - if (isNaN(threads) || threads < 1) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument for thread count passed into exec(). Must be numeric and greater than 0"); - } - var argsForNewScript = []; - for (var i = 3; i < arguments.length; ++i) { - argsForNewScript.push(arguments[i]); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["runScriptFromScript"])(server, scriptname, argsForNewScript, workerScript, threads); - }, - spawn : function(scriptname, threads) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.spawn) { - return 0; - } else { - workerScript.loadedFns.spawn = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSpawnRamCost; - } - } - if (scriptname == null || threads == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()"); - } - setTimeout(()=>{ - NetscriptFunctions(workerScript).run.apply(this, arguments); - }, 20000); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.spawn == null) { - workerScript.scriptRef.log("spawn() will execute " + scriptname + " in 20 seconds"); - } - NetscriptFunctions(workerScript).exit(); - }, - kill : function(filename,ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.kill) { - return 0; - } else { - workerScript.loadedFns.kill = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost; - } - } - - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "kill() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForKillTarget = []; - for (var i = 2; i < arguments.length; ++i) { - argsForKillTarget.push(arguments[i]); - } - var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(filename, argsForKillTarget, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget)); - return false; - } - var res = Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(runningScriptObj, server.ip); - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die..."); - } - return true; - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.kill == null) { - workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForKillTarget)); - } - return false; - } - }, - killall : function(ip=workerScript.serverIp){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.killall) { - return 0; - } else { - workerScript.loadedFns.killall = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost; - } - } - - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip); - } - var scriptsRunning = (server.runningScripts.length > 0); - for (var i = server.runningScripts.length-1; i >= 0; --i) { - Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(server.runningScripts[i], server.ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.killall == null) { - workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die"); - } - return scriptsRunning; - }, - exit : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.exit) { - return 0; - } else { - workerScript.loadedFns.exit = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptKillRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in exit(). This is a bug please contact game dev"); - } - if (Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(workerScript.scriptRef, server.ip)) { - workerScript.scriptRef.log("Exiting..."); - } else { - workerScript.scriptRef.log("Exit failed(). This is a bug please contact game developer"); - } - }, - scp : function(scriptname, ip1, ip2) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.scp) { - return 0; - } else { - workerScript.loadedFns.scp = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScpRamCost; - } - } - if (arguments.length !== 2 && arguments.length !== 3) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - if (scriptname && scriptname.constructor === Array) { - //Recursively call scp on all elements of array - var res = false; - scriptname.forEach(function(script) { - if (NetscriptFunctions(workerScript).scp(script, ip1, ip2)) { - res = true; - }; - }); - return res; - } - if (!scriptname.endsWith(".lit") && !Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["isScriptFilename"])(scriptname) && - !scriptname.endsWith("txt")) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() does not work with this file type. It only works for .script, .lit, and .txt files"); - } - - var destServer, currServ; - - if (arguments.length === 3) { //scriptname, source, destination - if (scriptname === undefined || ip1 === undefined || ip2 === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip2); - if (destServer == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip1); - if (currServ == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } else if (arguments.length === 2) { //scriptname, destination - if (scriptname === undefined || ip1 === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: scp() call has incorrect number of arguments. Takes 2 or 3 arguments"); - } - destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip1); - if (destServer == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error: Invalid hostname/ip passed into scp() command: " + ip); - } - - currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (currServ == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer"); - } - } - - //Scp for lit files - if (scriptname.endsWith(".lit")) { - var found = false; - for (var i = 0; i < currServ.messages.length; ++i) { - if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && currServ.messages[i] == scriptname) { - found = true; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.messages.length; ++i) { - if (destServer.messages[i] === scriptname) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; //Already exists - } - } - destServer.messages.push(scriptname); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for text files - if (scriptname.endsWith(".txt")) { - var found = false, txtFile; - for (var i = 0; i < currServ.textFiles.length; ++i) { - if (currServ.textFiles[i].fn === scriptname) { - found = true; - txtFile = currServ.textFiles[i]; - break; - } - } - - if (!found) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - for (var i = 0; i < destServer.textFiles.length; ++i) { - if (destServer.textFiles[i].fn === scriptname) { - //Overwrite - destServer.textFiles[i].text = txtFile.text; - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - } - var newFile = new _TextFile_js__WEBPACK_IMPORTED_MODULE_22__["TextFile"](txtFile.fn, txtFile.text); - destServer.textFiles.push(newFile); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - } - - //Scp for script files - var sourceScript = null; - for (var i = 0; i < currServ.scripts.length; ++i) { - if (scriptname == currServ.scripts[i].filename) { - sourceScript = currServ.scripts[i]; - break; - } - } - if (sourceScript == null) { - workerScript.scriptRef.log(scriptname + " does not exist. scp() failed"); - return false; - } - - //Overwrite script if it already exists - for (var i = 0; i < destServer.scripts.length; ++i) { - if (scriptname == destServer.scripts[i].filename) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log("WARNING: " + scriptname + " already exists on " + destServer.hostname + " and it will be overwritten."); - workerScript.scriptRef.log(scriptname + " overwritten on " + destServer.hostname); - } - var oldScript = destServer.scripts[i]; - oldScript.code = sourceScript.code; - oldScript.ramUsage = sourceScript.ramUsage; - return true; - } - } - - //Create new script if it does not already exist - var newScript = new _Script_js__WEBPACK_IMPORTED_MODULE_16__["Script"](); - newScript.filename = scriptname; - newScript.code = sourceScript.code; - newScript.ramUsage = sourceScript.ramUsage; - newScript.server = destServer.ip; - destServer.scripts.push(newScript); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.scp == null) { - workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname); - } - return true; - }, - ls : function(ip, grep) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.ls) { - return 0; - } else { - workerScript.loadedFns.ls = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost; - } - } - if (ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ls() failed. Invalid IP or hostname passed in: " + ip); - } - - //Get the grep filter, if one exists - var filter = false; - if (arguments.length >= 2) { - filter = grep.toString(); - } - - var allFiles = []; - for (var i = 0; i < server.programs.length; i++) { - if (filter) { - if (server.programs[i].includes(filter)) { - allFiles.push(server.programs[i]); - } - } else { - allFiles.push(server.programs[i]); - } - } - for (var i = 0; i < server.scripts.length; i++) { - if (filter) { - if (server.scripts[i].filename.includes(filter)) { - allFiles.push(server.scripts[i].filename); - } - } else { - allFiles.push(server.scripts[i].filename); - } - - } - for (var i = 0; i < server.messages.length; i++) { - if (filter) { - if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) { - if (server.messages[i].filename.includes(filter)) { - allFiles.push(server.messages[i].filename); - } - } else if (server.messages[i].includes(filter)) { - allFiles.push(server.messages[i]); - } - } else { - if (server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) { - allFiles.push(server.messages[i].filename); - } else { - allFiles.push(server.messages[i]); - } - } - } - - for (var i = 0; i < server.textFiles.length; i++) { - if (filter) { - if (server.textFiles[i].fn.includes(filter)) { - allFiles.push(server.textFiles[i].fn); - } - } else { - allFiles.push(server.textFiles[i].fn); - } - } - - //Sort the files alphabetically then print each - allFiles.sort(); - return allFiles; - }, - hasRootAccess : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.hasRootAccess) { - return 0; - } else { - workerScript.loadedFns.hasRootAccess = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptHasRootAccessRamCost; - } - } - if (ip===undefined){ - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null){ - workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip); - } - return server.hasAdminRights; - }, - getIp : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getIp) { - return 0; - } else { - workerScript.loadedFns.getIp = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost; - } - } - var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.ip; - }, - getHostname : function(){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getHostname) { - return 0; - } else { - workerScript.loadedFns.getHostname = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHostnameRamCost; - } - } - var scriptServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (scriptServer == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev"); - } - return scriptServer.hostname; - }, - getHackingLevel : function(){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getHackingLevel) { - return 0; - } else { - workerScript.loadedFns.getHackingLevel = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackingLevelRamCost; - } - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].updateSkillLevels(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) { - workerScript.scriptRef.log("getHackingLevel() returned " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill); - } - return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill; - }, - getHackingMultipliers : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getHackingMultipliers) { - return 0; - } else { - workerScript.loadedFns.getHackingMultipliers = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost; - } - } - return { - chance: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_chance_mult, - speed: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_speed_mult, - money: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_money_mult, - growth: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_grow_mult, - }; - }, - getHacknetMultipliers : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getHacknetMultipliers) { - return 0; - } else { - workerScript.loadedFns.getHacknetMultipliers = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost; - } - } - return { - production: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_money_mult, - purchaseCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_purchase_cost_mult, - ramCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_ram_cost_mult, - coreCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_core_cost_mult, - levelCost: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacknet_node_level_cost_mult, - }; - }, - getBitNodeMultipliers: function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getBitNodeMultipliers) { - return 0; - } else { - workerScript.loadedFns.getBitNodeMultipliers = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetMultipliersRamCost; - } - } - if (!hasAISF) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getBitNodeMultipliers(). It requires Source-File 5 to run."); - } - let copy = Object.assign({}, _BitNode_js__WEBPACK_IMPORTED_MODULE_2__["BitNodeMultipliers"]); - return copy; - }, - getServerMoneyAvailable : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerMoneyAvailable) { - return 0; - } else { - workerScript.loadedFns.getServerMoneyAvailable = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip); - } - if (server.hostname == "home") { - //Return player's money - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.toNumber(), 2)); - } - return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.toNumber(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) { - workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.moneyAvailable, 2) + " for " + server.hostname); - } - return server.moneyAvailable; - }, - getServerSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerSecurityLevel) { - return 0; - } else { - workerScript.loadedFns.getServerSecurityLevel = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerSecurityLevel == null) { - workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.hackDifficulty, 3) + " for " + server.hostname); - } - return server.hackDifficulty; - }, - getServerBaseSecurityLevel : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerBaseSecurityLevel) { - return 0; - } else { - workerScript.loadedFns.getServerBaseSecurityLevel = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerBaseSecurityLevel == null) { - workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.baseDifficulty, 3) + " for " + server.hostname); - } - return server.baseDifficulty; - }, - getServerMinSecurityLevel : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerMinSecurityLevel) { - return 0; - } else { - workerScript.loadedFns.getServerMinSecurityLevel = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMinSecurityLevel == null) { - workerScript.scriptRef.log("getServerMinSecurityLevel() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.minDifficulty, 3) + " for " + server.hostname); - } - return server.minDifficulty; - }, - getServerRequiredHackingLevel : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerRequiredHackingLevel) { - return 0; - } else { - workerScript.loadedFns.getServerRequiredHackingLevel = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRequiredHackingLevel == null) { - workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.requiredHackingSkill, 0) + " for " + server.hostname); - } - return server.requiredHackingSkill; - }, - getServerMaxMoney : function(ip){ - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerMaxMoney) { - return 0; - } else { - workerScript.loadedFns.getServerMaxMoney = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMaxMoney == null) { - workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.moneyMax, 0) + " for " + server.hostname); - } - return server.moneyMax; - }, - getServerGrowth : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerGrowth) { - return 0; - } else { - workerScript.loadedFns.getServerGrowth = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerGrowth == null) { - workerScript.scriptRef.log("getServerGrowth() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.serverGrowth, 0) + " for " + server.hostname); - } - return server.serverGrowth; - }, - getServerNumPortsRequired : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerNumPortsRequired) { - return 0; - } else { - workerScript.loadedFns.getServerNumPortsRequired = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerNumPortsRequired == null) { - workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.numOpenPortsRequired, 0) + " for " + server.hostname); - } - return server.numOpenPortsRequired; - }, - getServerRam : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getServerRam) { - return 0; - } else { - workerScript.loadedFns.getServerRam = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerRam == null) { - workerScript.scriptRef.log("getServerRam() returned [" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(server.ramUsed, 2) + "GB]"); - } - return [server.maxRam, server.ramUsed]; - }, - serverExists : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.serverExists) { - return 0; - } else { - workerScript.loadedFns.serverExists = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetServerRamCost; - } - } - return (Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip) !== null); - }, - fileExists : function(filename,ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.fileExists) { - return 0; - } else { - workerScript.loadedFns.fileExists = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptFileExistsRamCost; - } - } - if (filename === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "fileExists() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (filename == server.scripts[i].filename) { - return true; - } - } - for (var i = 0; i < server.programs.length; ++i) { - if (filename.toLowerCase() == server.programs[i].toLowerCase()) { - return true; - } - } - for (var i = 0; i < server.messages.length; ++i) { - if (!(server.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && - filename.toLowerCase() === server.messages[i]) { - return true; - } - } - var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(filename, server); - if (txtFile != null) { - return true; - } - return false; - }, - isRunning : function(filename,ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.isRunning) { - return 0; - } else { - workerScript.loadedFns.isRunning = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptIsRunningRamCost; - } - } - if (filename === undefined || ip === undefined) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)"); - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isRunning() failed. Invalid IP or hostname passed in: " + ip); - } - var argsForTargetScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForTargetScript.push(arguments[i]); - } - return (Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(filename, argsForTargetScript, server) != null); - }, - getNextHacknetNodeCost : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getNextHacknetNodeCost) { - return 0; - } else { - workerScript.loadedFns.getNextHacknetNodeCost = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost; - } - } - return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__["getCostOfNextHacknetNode"])(); - }, - - purchaseHacknetNode : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.purchaseHacknetNode) { - return 0; - } else { - workerScript.loadedFns.purchaseHacknetNode = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseHacknetRamCost; - } - } - return Object(_HacknetNode_js__WEBPACK_IMPORTED_MODULE_11__["purchaseHacknet"])(); - }, - getStockPrice : function(symbol) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getStockPrice) { - return 0; - } else { - workerScript.loadedFns.getStockPrice = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()"); - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPrice()"); - } - return parseFloat(stock.price.toFixed(3)); - }, - getStockPosition : function(symbol) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getStockPosition) { - return 0; - } else { - workerScript.loadedFns.getStockPosition = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()"); - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into getStockPosition()"); - } - return [stock.playerShares, stock.playerAvgPx, stock.playerShortShares, stock.playerAvgShortPx]; - }, - buyStock : function(symbol, shares) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.buyStock) { - return 0; - } else { - workerScript.loadedFns.buyStock = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()"); - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into buyStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()"); - return 0; - } - shares = Math.round(shares); - if (shares === 0) {return 0;} - - var totalPrice = stock.price * shares; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission)) { - workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + - symbol + ". Need $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission, 2).toString()); - return 0; - } - - var origTotal = stock.playerShares * stock.playerAvgPx; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission); - var newTotal = origTotal + totalPrice; - stock.playerShares += shares; - stock.playerAvgPx = newTotal / stock.playerShares; - if (_engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { - Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["updateStockPlayerPosition"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) { - workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(stock.price, 2) + " per share"); - } - return stock.price; - }, - sellStock : function(symbol, shares) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.sellStock) { - return 0; - } else { - workerScript.loadedFns.sellStock = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()"); - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid stock symbol passed into sellStock()"); - } - if (shares < 0 || isNaN(shares)) { - workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()"); - return 0; - } - shares = Math.round(shares); - if (shares > stock.playerShares) {shares = stock.playerShares;} - if (shares === 0) {return 0;} - var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainMoney(gains); - - //Calculate net profit and add to script stats - var netProfit = ((stock.price - stock.playerAvgPx) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission; - if (isNaN(netProfit)) {netProfit = 0;} - workerScript.scriptRef.onlineMoneyMade += netProfit; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug += netProfit; - - stock.playerShares -= shares; - if (stock.playerShares == 0) { - stock.playerAvgPx = 0; - } - if (_engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_9__["Engine"].Page.StockMarket) { - Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["updateStockPlayerPosition"])(stock); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) { - workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(stock.price, 2) + " per share. Gained " + - "$" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(gains, 2)); - } - return stock.price; - }, - shortStock(symbol, shares) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.shortStock) { - return 0; - } else { - workerScript.loadedFns.shortStock = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()"); - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use shortStock(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()"); - } - var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["shortStock"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - sellShort(symbol, shares) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.sellShort) { - return 0; - } else { - workerScript.loadedFns.sellShort = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()"); - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use sellShort(). You must either be in BitNode-8 or you must have Level 2 of Source-File 8"); - } - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()"); - } - var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["sellShort"])(stock, shares, workerScript); - return res ? stock.price : 0; - }, - placeOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.placeOrder) { - return 0; - } else { - workerScript.loadedFns.placeOrder = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()"); - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use placeOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into placeOrder()"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopSell; - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Short; - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - - return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["placeOrder"])(stock, shares, price, orderType, orderPos, workerScript); - }, - cancelOrder(symbol, shares, price, type, pos) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.cancelOrder) { - return 0; - } else { - workerScript.loadedFns.cancelOrder = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBuySellStockRamCost; - } - } - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hasTixApiAccess) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()"); - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 8) { - if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Cannot use cancelOrder(). You must either be in BitNode-8 or have Level 3 of Source-File 8"); - } - } - var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["SymbolToStockMap"][symbol]; - if (stock == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()"); - } - if (isNaN(shares) || isNaN(price)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid shares or price argument passed into cancelOrder(). Must be numeric"); - } - var orderType, orderPos; - type = type.toLowerCase(); - if (type.includes("limit") && type.includes("buy")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitBuy; - } else if (type.includes("limit") && type.includes("sell")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].LimitSell; - } else if (type.includes("stop") && type.includes("buy")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopBuy; - } else if (type.includes("stop") && type.includes("sell")) { - orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["OrderTypes"].StopSell; - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()"); - } - - pos = pos.toLowerCase(); - if (pos.includes("l")) { - orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Long; - } else if (pos.includes('s')) { - orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["PositionTypes"].Short; - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()"); - } - var params = { - stock: stock, - shares: shares, - price: price, - type: orderType, - pos: orderPos - }; - return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_20__["cancelOrder"])(params, workerScript); - }, - purchaseServer : function(hostname, ram) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.purchaseServer) { - return 0; - } else { - workerScript.loadedFns.purchaseServer = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost; - } - } - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s+/g, ''); - if (hostnameStr == "") { - workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()"); - return ""; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.length >= _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit) { - workerScript.scriptRef.log("Error: You have reached the maximum limit of " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerLimit + - " servers. You cannot purchase any more."); - return ""; - } - - ram = Math.round(ram); - if (isNaN(ram) || !Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["powerOfTwo"])(ram)) { - workerScript.scriptRef.log("Error: purchaseServer() failed due to invalid ram argument. Must be numeric and a power of 2"); - return ""; - } - - if (ram > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam) { - workerScript.scriptRef.log("Error: purchasedServer() failed because specified RAM was too high. Maximum RAM on a purchased server is " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].PurchasedServerMaxRam + "GB"); - return ""; - } - - var cost = ram * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamServer; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(cost)) { - workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(cost, 2)); - return ""; - } - var newServ = new _Server_js__WEBPACK_IMPORTED_MODULE_17__["Server"]({ - ip: Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__["createRandomIp"])(), - hostname: hostnameStr, - organizationName: "", - isConnectedTo: false, - adminRights: true, - purchasedByPlayer: true, - maxRam: ram, - }); - Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["AddToAllServers"])(newServ); - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.push(newServ.ip); - var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); - homeComputer.serversOnNetwork.push(newServ.ip); - newServ.serversOnNetwork.push(homeComputer.ip); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(cost); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseServer == null) { - workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["formatNumber"])(cost, 2)); - } - return newServ.hostname; - }, - deleteServer : function(hostname) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.deleteServer) { - return 0; - } else { - workerScript.loadedFns.deleteServer = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost; - } - } - var hostnameStr = String(hostname); - hostnameStr = hostnameStr.replace(/\s\s+/g, ''); - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["GetServerByHostname"])(hostnameStr); - if (server == null) { - workerScript.scriptRef.log("Error: Could not find server with hostname " + hostnameStr + ". deleteServer() failed"); - return false; - } - - if (!server.purchasedByPlayer || server.hostname === "home") { - workerScript.scriptRef.log("Error: Server " + server.hostname + " is not a purchased server. " + - "Cannot be deleted. deleteServer() failed"); - return false; - } - - var ip = server.ip; - - //Can't delete server you're currently connected to - if (server.isConnectedTo) { - workerScript.scriptRef.log("Error: deleteServer() failed because you are currently connected to the server you are trying to delete"); - return false; - } - - //A server cannot delete itself - if (ip === workerScript.serverIp) { - workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. deleteServer() failed"); - return false; - } - - //Delete all scripts running on server - if (server.runningScripts.length > 0) { - workerScript.scriptRef.log("Error: Cannot delete server " + server.hostname + " because it still has scripts running."); - return false; - } - - //Delete from player's purchasedServers array - var found = false; - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.length; ++i) { - if (ip == _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers[i]) { - found = true; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.splice(i, 1); - break; - } - } - - if (!found) { - workerScript.scriptRef.log("Error: Could not identify server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - } - - //Delete from all servers - delete _Server_js__WEBPACK_IMPORTED_MODULE_17__["AllServers"][ip]; - - //Delete from home computer - found = false; - var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); - for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) { - if (ip == homeComputer.serversOnNetwork[i]) { - homeComputer.serversOnNetwork.splice(i, 1); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.deleteServer == null) { - workerScript.scriptRef.log("Deleted server " + hostnameStr); - } - return true; - } - } - //Wasn't found on home computer - workerScript.scriptRef.log("Error: Could not find server " + server.hostname + - "as a purchased server. This is likely a bug please contact game dev"); - return false; - }, - getPurchasedServers : function(hostname=true) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getPurchasedServers) { - return 0; - } else { - workerScript.loadedFns.getPurchasedServers = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptPurchaseServerRamCost; - } - } - var res = []; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].purchasedServers.forEach(function(ip) { - if (hostname) { - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find server in getPurchasedServers(). This is a bug please report to game dev"); - } - res.push(server.hostname); - } else { - res.push(ip); - } - }); - return res; - }, - write : function(port, data="", mode="a") { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.write) { - return 0; - } else { - workerScript.loadedFns.write = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost; - } - } - if (!isNaN(port)) { //Write to port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to write to invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.write(data); - } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Write to text file - var fn = port; - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); - if (txtFile == null) { - txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["createTextFile"])(fn, data, server); - return true; - } - if (mode === "w") { - txtFile.write(data); - } else { - txtFile.append(data); - } - return true; - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for write: " + port); - } - }, - read : function(port) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.read) { - return 0; - } else { - workerScript.loadedFns.read = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost; - } - } - if (!isNaN(port)) { //Read from port - //Port 1-10 - port = Math.round(port); - if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to read from invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid."); - } - var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.read(); - } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Read from text file - var fn = port; - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); - if (txtFile !== null) { - return txtFile.text; - } else { - return ""; - } - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for read(): " + port); - } - }, - peek : function(port) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.peek) { - return 0; - } else { - workerScript.loadedFns.peek = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost; - } - } - if (isNaN(port)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: peek() called with invalid argument. Must be a port number between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.peek(); - }, - clear : function(port) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.clear) { - return 0; - } else { - workerScript.loadedFns.clear = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost; - } - } - if (!isNaN(port)) { //Clear port - port = Math.round(port); - if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Trying to clear invalid port: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port.clear(); - } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(port)) { //Clear text file - var fn = port; - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (server == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - var txtFile = Object(_TextFile_js__WEBPACK_IMPORTED_MODULE_22__["getTextFile"])(fn, server); - if (txtFile != null) { - txtFile.write(""); - } - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid argument passed in for clear(): " + port); - } - return 0; - }, - getPortHandle : function(port) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getPortHandle) { - return 0; - } else { - workerScript.loadedFns.getPortHandle = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost * 10; - } - } - if (isNaN(port)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Invalid argument passed into getPortHandle(). Must be an integer between 1 and " + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts); - } - port = Math.round(port); - if (port < 1 || port > _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: getPortHandle() called with invalid port number: " + port + ". Only ports 1-" + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].NumNetscriptPorts + " are valid"); - } - var port = _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["NetscriptPorts"][port-1]; - if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_26__["NetscriptPort"])) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "ERR: Could not find port: " + port + ". This is a bug contact the game developer"); - } - return port; - }, - rm : function(fn) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.rm) { - return 0; - } else { - workerScript.loadedFns.rm = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptReadWriteRamCost; - } - } - var s = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(workerScript.serverIp); - if (s == null) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev"); - } - - if (fn.includes(".exe")) { - for (var i = 0; i < s.programs.length; ++i) { - if (s.programs[i] === fn) { - s.programs.splice(i, 1); - return true; - } - } - } else if (Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["isScriptFilename"])(fn)) { - for (var i = 0; i < s.scripts.length; ++i) { - if (s.scripts[i].filename === fn) { - //Check that the script isnt currently running - for (var j = 0; j < s.runningScripts.length; ++j) { - if (s.runningScripts[j].filename === fn) { - workerScript.scriptRef.log("Cannot delete a script that is currently running!"); - return false; - } - } - s.scripts.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".lit")) { - for (var i = 0; i < s.messages.length; ++i) { - var f = s.messages[i]; - if (!(f instanceof _Message_js__WEBPACK_IMPORTED_MODULE_13__["Message"]) && Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(f) && f === fn) { - s.messages.splice(i, 1); - return true; - } - } - } else if (fn.endsWith(".txt")) { - for (var i = 0; i < s.textFiles.length; ++i) { - if (s.textFiles[i].fn === fn) { - s.textFiles.splice(i, 1); - return true; - } - } - } - return false; - }, - scriptRunning : function(scriptname, ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.scriptRunning) { - return 0; - } else { - workerScript.loadedFns.scriptRunning = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "scriptRunning() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - return true; - } - } - return false; - }, - scriptKill : function(scriptname, ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.scriptKill) { - return 0; - } else { - workerScript.loadedFns.scriptKill = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptArbScriptRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "scriptKill() failed. Invalid IP or hostname passed in: " + ip); - } - var suc = false; - for (var i = 0; i < server.runningScripts.length; ++i) { - if (server.runningScripts[i].filename == scriptname) { - Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["killWorkerScript"])(server.runningScripts[i], server.ip); - suc = true; - } - } - return suc; - }, - getScriptName : function() { - if (workerScript.checkingRam) {return 0;} - return workerScript.name; - }, - getScriptRam : function (scriptname, ip=workerScript.serverIp) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getScriptRam) { - return 0; - } else { - workerScript.loadedFns.getScriptRam = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptRam() failed. Invalid IP or hostname passed in: " + ip); - } - for (var i = 0; i < server.scripts.length; ++i) { - if (server.scripts[i].filename == scriptname) { - return server.scripts[i].ramUsage; - } - } - return 0; - }, - getHackTime : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getHackTime) { - return 0; - } else { - workerScript.loadedFns.getHackTime = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateHackingTime"])(server); //Returns seconds - }, - getGrowTime : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getGrowTime) { - return 0; - } else { - workerScript.loadedFns.getGrowTime = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateGrowTime"])(server) / 1000; //Returns seconds - }, - getWeakenTime : function(ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getWeakenTime) { - return 0; - } else { - workerScript.loadedFns.getWeakenTime = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost; - } - } - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip); - } - return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["scriptCalculateWeakenTime"])(server) / 1000; //Returns seconds - }, - getScriptIncome : function(scriptname, ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getScriptIncome) { - return 0; - } else { - workerScript.loadedFns.getScriptIncome = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost; - } - } - if (arguments.length === 0) { - //Get total script income - var res = []; - res.push(Object(_ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__["updateActiveScriptsItems"])()); - res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].playtimeSinceLastAug/1000)); - return res; - } else { - //Get income for a particular script - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptIncome() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineMoneyMade / runningScriptObj.onlineRunningTime; - } - }, - getScriptExpGain : function(scriptname, ip) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getScriptExpGain) { - return 0; - } else { - workerScript.loadedFns.getScriptExpGain = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetScriptRamCost; - } - } - if (arguments.length === 0) { - var total = 0; - for (var i = 0; i < _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"].length; ++i) { - total += (_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"][i].scriptRef.onlineExpGained / _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_23__["workerScripts"][i].scriptRef.onlineRunningTime); - } - return total; - } else { - //Get income for a particular script - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["getServer"])(ip); - if (server == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip); - } - var argsForScript = []; - for (var i = 2; i < arguments.length; ++i) { - argsForScript.push(arguments[i]); - } - var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_16__["findRunningScript"])(scriptname, argsForScript, server); - if (runningScriptObj == null) { - workerScript.scriptRef.log("getScriptExpGain() failed. No such script "+ scriptname + " on " + server.hostname + " with args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_29__["printArray"])(argsForScript)); - return -1; - } - return runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime; - } - }, - getTimeSinceLastAug : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getTimeSinceLastAug) { - return 0; - } else { - workerScript.loadedFns.getTimeSinceLastAug = true; - return _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptGetHackTimeRamCost; - } - } - return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].playtimeSinceLastAug; - }, - prompt : function(txt) { - if (workerScript.checkingRam) {return 0;} - if (_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxOpen"]) { - workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open"); - return false; - } - if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(txt)) {txt = String(txt);} - var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxGetNoButton"])(); - yesBtn.innerHTML = "Yes"; - noBtn.innerHTML = "No"; - return new Promise(function(resolve, reject) { - yesBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxClose"])(); - resolve(true); - }); - noBtn.addEventListener("click", ()=>{ - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxClose"])(); - resolve(false); - }); - Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_32__["yesNoBoxCreate"])(txt); - }); - }, - - /* Singularity Functions */ - universityCourse : function(universityName, className) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.universityCourse) { - return 0; - } else { - workerScript.loadedFns.universityCourse = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission."); - return; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log(txt); - } - } - - var costMult, expMult; - switch(universityName.toLowerCase()) { - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSummitUniversity.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSummitUniversity; - costMult = 4; - expMult = 3; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12RothmanUniversity.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12RothmanUniversity; - costMult = 3; - expMult = 2; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenZBInstituteOfTechnology; - costMult = 5; - expMult = 4; - break; - default: - workerScript.scriptRef.log("Invalid university name: " + universityName + ". universityCourse() failed"); - return false; - } - - var task; - switch(className.toLowerCase()) { - case "Study Computer Science".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassStudyComputerScience; - break; - case "Data Structures".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassDataStructures; - break; - case "Networks".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassNetworks; - break; - case "Algorithms".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassAlgorithms; - break; - case "Management".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassManagement; - break; - case "Leadership".toLowerCase(): - task = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassLeadership; - break; - default: - workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, task); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.universityCourse == null) { - workerScript.scriptRef.log("Started " + task + " at " + universityName); - } - return true; - }, - - gymWorkout : function(gymName, stat) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.gymWorkout) { - return 0; - } else { - workerScript.loadedFns.gymWorkout = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission."); - return; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log(txt); - } - } - var costMult, expMult; - switch(gymName.toLowerCase()) { - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumCrushFitnessGym.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumCrushFitnessGym; - costMult = 3; - expMult = 2; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSnapFitnessGym.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum) { - workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSnapFitnessGym; - costMult = 10; - expMult = 5; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12IronGym.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12IronGym; - costMult = 1; - expMult = 1; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12PowerhouseGym.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12) { - workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12PowerhouseGym; - costMult = 20; - expMult = 10; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenMilleniumFitnessGym: - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven) { - workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenMilleniumFitnessGym; - costMult = 7; - expMult = 4; - break; - default: - workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed"); - return false; - } - - switch(stat.toLowerCase()) { - case "strength".toLowerCase(): - case "str".toLowerCase(): - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymStrength); - break; - case "defense".toLowerCase(): - case "def".toLowerCase(): - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDefense); - break; - case "dexterity".toLowerCase(): - case "dex".toLowerCase(): - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDexterity); - break; - case "agility".toLowerCase(): - case "agi".toLowerCase(): - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymAgility); - break; - default: - workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed"); - return false; - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.gymWorkout == null) { - workerScript.scriptRef.log("Started training " + stat + " at " + gymName); - } - return true; - }, - - travelToCity(cityname) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.travelToCity) { - return 0; - } else { - workerScript.loadedFns.travelToCity = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 2; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - switch(cityname) { - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum: - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Chongqing: - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12: - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyo: - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Ishima: - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(200000); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city = cityname; - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.travelToCity == null) { - workerScript.scriptRef.log("Traveled to " + cityname); - } - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity()."); - return false; - } - }, - - purchaseTor() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.purchaseTor) { - return 0; - } else { - workerScript.loadedFns.purchaseTor = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"]["Darkweb Server"] != null) { - workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed"); - return false; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost)) { - workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost); - - var darkweb = new _Server_js__WEBPACK_IMPORTED_MODULE_17__["Server"]({ - ip:Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_30__["createRandomIp"])(), hostname:"darkweb", organizationName:"", - isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1 - }); - Object(_Server_js__WEBPACK_IMPORTED_MODULE_17__["AddToAllServers"])(darkweb); - _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip); - - document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive"); - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip); - darkweb.serversOnNetwork.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().ip); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseTor == null) { - workerScript.scriptRef.log("You have purchased a Tor router!"); - } - return true; - }, - purchaseProgram(programName) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.purchaseProgram) { - return 0; - } else { - workerScript.loadedFns.purchaseProgram = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - - if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"]["Darkweb Server"] == null) { - workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed."); - return false; - } - - switch(programName.toLowerCase()) { - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].BruteSSHProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].FTPCrackProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].RelaySMTPProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].HTTPWormProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].SQLInjectProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].DeepScanV1Program); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2.toLowerCase(): - var price = Object(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["parseDarkwebItemPrice"])(_DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"].DeepScanV2Program); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) { - workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program can be found on your home computer."); - } - } else { - workerScript.scriptRef.log("Not enough money to purchase " + programName); - return false; - } - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram()."); - return false; - } - return true; - }, - getStats : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getStats) { - return 0; - } else { - workerScript.loadedFns.getStats = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getStats(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - return { - hacking: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill, - strength: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].strength, - defense: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].defense, - dexterity: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].dexterity, - agility: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].agility, - charisma: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].charisma, - intelligence: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].intelligence - } - }, - getCharacterInformation : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getCharacterInformation) { - return 0; - } else { - workerScript.loadedFns.getCharacterInformation = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCharacterInformation(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return {}; - } - } - - var companyPositionTitle = ""; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"]) { - companyPositionTitle = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName; - } - return { - bitnode: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN, - company: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyName, - jobTitle: companyPositionTitle, - city: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city, - factions: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factions.slice(), - tor: _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_19__["SpecialServerIps"].hasOwnProperty("Darkweb Server"), - timeWorked: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].timeWorked, - workHackExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workHackExpGained, - workStrExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workStrExpGained, - workDefExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workDefExpGained, - workDexExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workDexExpGained, - workAgiExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workAgiExpGained, - workChaExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workChaExpGained, - workRepGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workRepGained, - workMoneyGain: _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].workMoneyGained, - }; - }, - isBusy : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.isBusy) { - return 0; - } else { - workerScript.loadedFns.isBusy = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run isBusy(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return; - } - } - return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking; - }, - stopAction : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.stopAction) { - return 0; - } else { - workerScript.loadedFns.stopAction = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 2; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 1)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run stopAction(). It is a Singularity Function and requires SourceFile-4 (level 1) to run."); - return false; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.stopAction == null) { - workerScript.scriptRef.log(txt); - } - return true; - } - return false; - }, - upgradeHomeRam : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.upgradeHomeRam) { - return 0; - } else { - workerScript.loadedFns.upgradeHomeRam = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - //Calculate how many times ram has been upgraded (doubled) - var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().maxRam; - var numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamHome; - var mult = Math.pow(1.55, numUpgrades); - cost = cost * mult; - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].money.lt(cost)) { - workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money"); - return false; - } - - var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer(); - homeComputer.maxRam *= 2; - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].loseMoney(cost); - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.upgradeHomeRam == null) { - workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM."); - } - return true; - }, - getUpgradeHomeRamCost : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getUpgradeHomeRamCost) { - return 0; - } else { - workerScript.loadedFns.getUpgradeHomeRamCost = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 2; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - //Calculate how many times ram has been upgraded (doubled) - var currentRam = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].getHomeComputer().maxRam; - var numUpgrades = Math.log2(currentRam); - - //Calculate cost - //Have cost increase by some percentage each time RAM has been upgraded - var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].BaseCostFor1GBOfRamHome; - var mult = Math.pow(1.55, numUpgrades); - return cost * mult; - }, - workForCompany : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.workForCompany) { - return 0; - } else { - workerScript.loadedFns.workForCompany = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission."); - return; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition == "" || !(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"])) { - workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job"); - return false; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log(txt); - } - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.isPartTimeJob()) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startWorkPartTime(); - } else { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startWork(); - } - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) { - workerScript.scriptRef.log("Began working at " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName); - } - return true; - }, - applyToCompany : function(companyName, field) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.applyToCompany) { - return 0; - } else { - workerScript.loadedFns.applyToCompany = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Company_js__WEBPACK_IMPORTED_MODULE_5__["companyExists"])(companyName)) { - workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist."); - return false; - } - - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = companyName; - var res; - switch (field.toLowerCase()) { - case "software": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSoftwareJob(true); - break; - case "software consultant": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSoftwareConsultantJob(true); - break; - case "it": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForItJob(true); - break; - case "security engineer": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSecurityEngineerJob(true); - break; - case "network engineer": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForNetworkEngineerJob(true); - break; - case "business": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForBusinessJob(true); - break; - case "business consultant": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForBusinessConsultantJob(true); - break; - case "security": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForSecurityJob(true); - break; - case "agent": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForAgentJob(true); - break; - case "employee": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForEmployeeJob(true); - break; - case "part-time employee": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForPartTimeEmployeeJob(true); - break; - case "waiter": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForWaiterJob(true); - break; - case "part-time waiter": - res = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].applyForPartTimeWaiterJob(true); - break; - default: - workerScript.scriptRef.log("ERROR: Invalid job passed into applyToCompany: " + field + ". applyToCompany() failed"); - return false; - } - //The Player object's applyForJob function can return string with special error messages - if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(res)) { - workerScript.scriptRef.log(res); - return false; - } - if (res) { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].companyPosition.positionName); - } - } else { - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.applyToCompany == null) { - workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field."); - } - } - return res; - }, - getCompanyRep : function(companyName) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getCompanyRep) { - return 0; - } else { - workerScript.loadedFns.getCompanyRep = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company_js__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; - if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["Company"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName); - return -1; - } - return company.playerReputation; - }, - getCompanyFavor : function(companyName) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getCompanyFavor) { - return 0; - } else { - workerScript.loadedFns.getCompanyFavor = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCompanyFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - var company = _Company_js__WEBPACK_IMPORTED_MODULE_5__["Companies"][companyName]; - if (company == null || !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["Company"])) { - workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyFavor(): " + companyName); - return -1; - } - return company.favor; - }, - checkFactionInvitations : function() { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.checkFactionInvitations) { - return 0; - } else { - workerScript.loadedFns.checkFactionInvitations = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run checkFactionInvitations(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - //Make a copy of Player.factionInvitations - return _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.slice(); - }, - joinFaction : function(name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.joinFaction) { - return 0; - } else { - workerScript.loadedFns.joinFaction = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist."); - return false; - } - - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.includes(name)) { - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - - var index = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.indexOf(name); - if (index === -1) { - //Redundant and should never happen... - workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factionInvitations.splice(index, 1); - var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name]; - Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["joinFaction"])(fac); - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.joinFaction == null) { - workerScript.scriptRef.log("Joined the " + name + " faction."); - } - return true; - }, - workForFaction : function(name, type) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.workForFaction) { - return 0; - } else { - workerScript.loadedFns.workForFaction = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return false; - } - } - - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission."); - return; - } - - if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist."); - return false; - } - - if (!_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].factions.includes(name)) { - workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name); - return false; - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) { - workerScript.scriptRef.log(txt); - } - } - - var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name]; - //Arrays listing factions that allow each time of work - var hackAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "BitRunners", "The Black Hand", - "NiteSec", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Netburners", "Tian Di Hui", "CyberSec"]; - var fdWkAvailable = ["Illuminati", "Daedalus", "The Covenant", "ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", "The Dark Army", - "The Syndicate", "Silhouette", "Tetrads", "Slum Snakes"]; - var scWkAvailable = ["ECorp", "MegaCorp", - "Bachman & Associates", "Blade Industries", "NWO", "Clarke Incorporated", - "OmniTek Incorporated", "Four Sigma", "KuaiGong International", - "Fulcrum Secret Technologies", "Chongqing", "Sector-12", "New Tokyo", "Aevum", - "Ishima", "Volhaven", "Speakers for the Dead", - "The Syndicate", "Tetrads", "Slum Snakes", "Tian Di Hui"]; - - switch (type.toLowerCase()) { - case "hacking": - case "hacking contracts": - case "hackingcontracts": - if (!hackAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out hacking contracts for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionHackWork(fac); - workerScript.scriptRef.log("Started carrying out hacking contracts for " + fac.name); - return true; - case "field": - case "fieldwork": - case "field work": - if (!fdWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot carry out field missions for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionFieldWork(fac); - workerScript.scriptRef.log("Started carrying out field missions for " + fac.name); - return true; - case "security": - case "securitywork": - case "security work": - if (!scWkAvailable.includes(fac.name)) { - workerScript.scriptRef.log("ERROR: Cannot serve as security detail for " + fac.name + ". workForFaction() failed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startFactionSecurityWork(fac); - workerScript.scriptRef.log("Started serving as security details for " + fac.name); - return true; - default: - workerScript.scriptRef.log("ERROR: Invalid work type passed into workForFaction(): " + type); - } - return true; - }, - getFactionRep : function(name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getFactionRep) { - return 0; - } else { - workerScript.loadedFns.getFactionRep = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist."); - return -1; - } - - return _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name].playerReputation; - }, - getFactionFavor : function(name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getFactionFavor) { - return 0; - } else { - workerScript.loadedFns.getFactionFavor = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost / 4; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 2)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getFactionFavor(). It is a Singularity Function and requires SourceFile-4 (level 2) to run."); - return -1; - } - } - - if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(name)) { - workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist."); - return -1; - } - - return _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][name].favor; - }, - createProgram : function(name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.createProgram) { - return 0; - } else { - workerScript.loadedFns.createProgram = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission."); - return; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) { - workerScript.scriptRef.log(txt); - } - } - - switch(name.toLowerCase()) { - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram.toLowerCase(): - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerFiveMinutes, 1); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 50) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerFiveMinutes * 2, 50); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 100) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerHalfHour, 100); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 250) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer2Hours, 250); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 500) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer4Hours, 500); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 750) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer8Hours, 750); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 75) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV1, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerQuarterHour, 75); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 400) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].DeepscanV2, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPer2Hours, 400); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].ServerProfiler.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 75) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].ServerProfiler, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerHalfHour, 75); - break; - case _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].AutoLink.toLowerCase(): - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].hacking_skill < 25) { - workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].startCreateProgramWork(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].AutoLink, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].MillisecondsPerQuarterHour, 25); - break; - default: - workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name); - return false; - } - workerScript.scriptRef.log("Began creating program: " + name); - return true; - }, - commitCrime : function(crime) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.commitCrime) { - return 0; - } else { - workerScript.loadedFns.commitCrime = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run commitCrime(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - if (_Missions_js__WEBPACK_IMPORTED_MODULE_14__["inMission"]) { - workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission."); - return; - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].isWorking) { - var txt = _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].singularityStopWork(); - if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null) { - workerScript.scriptRef.log(txt); - } - } - - //Set Location to slums - switch(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].city) { - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Aevum: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].AevumSlums; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Chongqing: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].ChongqingSlums; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Sector12Slums; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyo: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].NewTokyoSlums; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Ishima: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].IshimaSlums; - break; - case _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].Volhaven: - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_12__["Locations"].VolhavenSlums; - break; - default: - console.log("Invalid Player.city value"); - } - - crime = crime.toLowerCase(); - let enableCommitCrimeLog = workerScript.disableLogs.ALL == null && workerScript.disableLogs.commitCrime == null - if (crime.includes("shoplift")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to shoplift...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitShopliftCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("rob") && crime.includes("store")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to rob a store...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitRobStoreCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("mug")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to mug someone...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitMugCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("larceny")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to commit larceny...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitLarcenyCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("drugs")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to deal drugs...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitDealDrugsCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("bond") && crime.includes("forge")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to forge corporate bonds...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitBondForgeryCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("traffick") && crime.includes("arms")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to traffick illegal arms...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitTraffickArmsCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("homicide")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to commit homicide...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitHomicideCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("grand") && crime.includes("auto")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to commit grand theft auto...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitGrandTheftAutoCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("kidnap")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to kidnap and ransom a high-profile target...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitKidnapCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else if (crime.includes("assassinate")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to assassinate a high-profile target...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitAssassinationCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}) - } else if (crime.includes("heist")) { - if(enableCommitCrimeLog) {workerScript.scriptRef.log("Attempting to pull off a heist...");} - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["commitHeistCrime"])(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].CrimeSingFnDivider, {workerscript: workerScript}); - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into commitCrime(): " + crime); - } - }, - getCrimeChance : function(crime) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getCrimeChance) { - return 0; - } else { - workerScript.loadedFns.getCrimeChance = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getCrimeChance(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return; - } - } - - crime = crime.toLowerCase(); - if (crime.includes("shoplift")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceShoplift"])(); - } else if (crime.includes("rob") && crime.includes("store")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceRobStore"])(); - } else if (crime.includes("mug")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceMug"])(); - } else if (crime.includes("larceny")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceLarceny"])(); - } else if (crime.includes("drugs")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceDealDrugs"])(); - } else if (crime.includes("bond") && crime.includes("forge")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceBondForgery"])(); - } else if (crime.includes("traffick") && crime.includes("arms")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceTraffickArms"])(); - } else if (crime.includes("homicide")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceHomicide"])(); - } else if (crime.includes("grand") && crime.includes("auto")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceGrandTheftAuto"])(); - } else if (crime.includes("kidnap")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceKidnap"])(); - } else if (crime.includes("assassinate")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceAssassination"])(); - } else if (crime.includes("heist")) { - return Object(_Crimes_js__WEBPACK_IMPORTED_MODULE_3__["determineCrimeChanceHeist"])(); - } else { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Invalid crime passed into getCrimeChance(): " + crime); - } - }, - getOwnedAugmentations : function(purchased=false) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getOwnedAugmentations) { - return 0; - } else { - workerScript.loadedFns.getOwnedAugmentations = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getOwnedAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - var res = []; - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations.length; ++i) { - res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations[i].name); - } - if (purchased) { - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length; ++i) { - res.push(_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations[i].name); - } - } - return res; - }, - getAugmentationsFromFaction : function(facname) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getAugmentationsFromFaction) { - return 0; - } else { - workerScript.loadedFns.getAugmentationsFromFaction = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationsFromFaction(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return []; - } - } - - if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["factionExists"])(facname)) { - workerScript.scriptRef.log("ERROR: getAugmentationsFromFaction() failed. Invalid faction name passed in (this is case-sensitive): " + facname); - return []; - } - - var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][facname]; - var res = []; - for (var i = 0; i < fac.augmentations.length; ++i) { - res.push(fac.augmentations[i]); - } - return res; - }, - getAugmentationCost : function(name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.getAugmentationCost) { - return 0; - } else { - workerScript.loadedFns.getAugmentationCost = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (!Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["augmentationExists"])(name)) { - workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name); - return [-1, -1]; - } - - var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; - return [aug.baseRepRequirement, aug.baseCost]; - }, - purchaseAugmentation : function(faction, name) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.purchaseAugmentation) { - return 0; - } else { - workerScript.loadedFns.purchaseAugmentation = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Factions"][faction]; - if (fac == null || !(fac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_10__["Faction"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid faction name: " + faction); - return false; - } - - if (!fac.augmentations.includes(name)) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because the faction " + faction + " does not contain the " + name + " augmentation"); - return false; - } - - var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentations"][name]; - if (aug == null || !(aug instanceof _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["Augmentation"])) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name); - return false; - } - - var isNeuroflux = false; - if (aug.name === _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["AugmentationNames"].NeuroFluxGovernor) { - isNeuroflux = true; - } - - if (!isNeuroflux) { - for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length; ++j) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - for (var j = 0; j < _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations.length; ++j) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].augmentations[j].name === aug.name) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name); - return false; - } - } - } - - if (fac.playerReputation < aug.baseRepRequirement) { - workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you do not have enough reputation with " + fac.name); - return false; - } - - var res = Object(_Faction_js__WEBPACK_IMPORTED_MODULE_10__["purchaseAugmentation"])(aug, fac, true); - workerScript.scriptRef.log(res); - if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_31__["isString"])(res) && res.startsWith("You purchased")) { - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - return true; - } else { - return false; - } - }, - installAugmentations : function(cbScript) { - if (workerScript.checkingRam) { - if (workerScript.loadedFns.installAugmentations) { - return 0; - } else { - workerScript.loadedFns.installAugmentations = true; - var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost; - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN !== 4) {ramCost *= 8;} - return ramCost; - } - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN != 4) { - if (!(hasSingularitySF && singularitySFLvl >= 3)) { - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run."); - return false; - } - } - - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].queuedAugmentations.length === 0) { - workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed"); - return false; - } - _Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].IntelligenceSingFnBaseExpGain); - workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed"); - Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_1__["installAugmentations"])(cbScript); - return true; - }, - - //Bladeburner API - bladeburner : { - isContractName : function(name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - isOperationName : function(name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - isBlackOpName : function(name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - isGeneralActionName : function(name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - isSkillName : function(name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - startAction : function(type, name) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - stopAction : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionTime : function(type="", name="") { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionEstimatedSuccessChance : function(type="", name="") { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getActionCountRemaining : function(type="", name="") { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getRank : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillPoints : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getSkillLevel : function(skillName="") { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - upgradeSkill : function(skillName) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getTeamSize : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - setTeamSize : function(type="", name="", size) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedPopulation : function(cityName) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityEstimatedCommunities : function(cityName) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getCityChaos : function(cityName) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - switchCity : function(cityName) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - getStamina : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - }, - joinFaction : function() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_15__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) { - - } - throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_24__["makeRuntimeRejectMsg"])(workerScript, "isContractName() failed because you do not currently have access to the Bladeburner API. This is either because you are not currently employed " + - "at the Bladeburner division or because you do not have Source-File 7"); - } - } - } //End return -} //End NetscriptFunction() - - - - -/***/ }), -/* 32 */ +/* 28 */ /*!*****************************************!*\ !*** ./node_modules/jszip/lib/utils.js ***! \*****************************************/ @@ -34102,11 +27156,11 @@ function NetscriptFunctions(workerScript) { "use strict"; -var support = __webpack_require__(/*! ./support */ 50); -var base64 = __webpack_require__(/*! ./base64 */ 105); -var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 65); -var setImmediate = __webpack_require__(/*! core-js/library/fn/set-immediate */ 167); -var external = __webpack_require__(/*! ./external */ 58); +var support = __webpack_require__(/*! ./support */ 46); +var base64 = __webpack_require__(/*! ./base64 */ 104); +var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62); +var setImmediate = __webpack_require__(/*! core-js/library/fn/set-immediate */ 166); +var external = __webpack_require__(/*! ./external */ 54); /** @@ -34579,7 +27633,1393 @@ exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinarySt /***/ }), -/* 33 */ +/* 29 */ +/*!****************************!*\ + !*** ./src/StockMarket.js ***! + \****************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockMarket", function() { return StockMarket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StockSymbols", function() { return StockSymbols; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SymbolToStockMap", function() { return SymbolToStockMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockSymbols", function() { return initStockSymbols; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStockMarket", function() { return initStockMarket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSymbolToStockMap", function() { return initSymbolToStockMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stockMarketCycle", function() { return stockMarketCycle; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyStock", function() { return buyStock; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellStock", function() { return sellStock; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shortStock", function() { return shortStock; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sellShort", function() { return sellShort; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPrices", function() { return updateStockPrices; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayStockMarketContent", function() { return displayStockMarketContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockTicker", function() { return updateStockTicker; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateStockPlayerPosition", function() { return updateStockPlayerPosition; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadStockMarket", function() { return loadStockMarket; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStockMarketContentCreated", function() { return setStockMarketContentCreated; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "placeOrder", function() { return placeOrder; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cancelOrder", function() { return cancelOrder; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Order", function() { return Order; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OrderTypes", function() { return OrderTypes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionTypes", function() { return PositionTypes; }); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Location.js */ 4); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9__); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); + + + + + + + + + + + + + + +let StockPriceCap = 1e9; //Put a limit on how high a price can go + +function Stock(name, symbol, mv, b, otlkMag, initPrice=10000) { + this.symbol = symbol; + this.name = name; + this.price = initPrice; + + this.playerShares = 0; + this.playerAvgPx = 0; + this.playerShortShares = 0; + this.playerAvgShortPx = 0; + this.mv = mv; + this.b = b; + this.otlkMag = otlkMag; + + this.posTxtEl = null; +} + +Stock.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Stock", this); +} + +Stock.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Stock, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Stock = Stock; + +var OrderTypes = { + LimitBuy: "Limit Buy Order", + LimitSell: "Limit Sell Order", + StopBuy: "Stop Buy Order", + StopSell: "Stop Sell Order" +} + +var PositionTypes = { + Long: "L", + Short: "S" +} + +function placeOrder(stock, shares, price, type, position, workerScript=null) { + var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); + var order = new Order(stock, shares, price, type, position); + if (isNaN(shares) || isNaN(price)) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: Invalid numeric value provided for either 'shares' or 'price' argument"); + } + return false; + } + if (StockMarket["Orders"] == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + } + StockMarket["Orders"][stock.symbol].push(order); + //Process to see if it should be executed immediately + processOrders(order.stock, order.type, order.pos); + updateStockOrderList(order.stock); + return true; +} + +//Returns true if successfully cancels an order, false otherwise +function cancelOrder(params, workerScript=null) { + var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); + if (StockMarket["Orders"] == null) {return false;} + if (params.order && params.order instanceof Order) { + var order = params.order; + //An 'Order' object is passed in + var stockOrders = StockMarket["Orders"][order.stock.symbol]; + for (var i = 0; i < stockOrders.length; ++i) { + if (order == stockOrders[i]) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + return true; + } + } + return false; + } else if (params.stock && params.shares && params.price && params.type && + params.pos && params.stock instanceof Stock) { + //Order properties are passed in. Need to look for the order + var stockOrders = StockMarket["Orders"][params.stock.symbol]; + var orderTxt = params.stock.symbol + " - " + params.shares + " @ " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(params.price).format('$0.000a'); + for (var i = 0; i < stockOrders.length; ++i) { + var order = stockOrders[i]; + if (params.shares === order.shares && + params.price === order.price && + params.type === order.type && + params.pos === order.pos) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + if (tixApi) { + workerScript.scriptRef.log("Successfully cancelled order: " + orderTxt); + } + return true; + } + } + if (tixApi) { + workerScript.scriptRef.log("Failed to cancel order: " + orderTxt); + } + return false; + } + return false; +} + +function executeOrder(order) { + var stock = order.stock; + var orderBook = StockMarket["Orders"]; + var stockOrders = orderBook[stock.symbol]; + var res = true; + console.log("Executing the following order:"); + console.log(order); + switch (order.type) { + case OrderTypes.LimitBuy: + case OrderTypes.StopBuy: + if (order.pos === PositionTypes.Long) { + res = buyStock(order.stock, order.shares) && res; + } else if (order.pos === PositionTypes.Short) { + res = shortStock(order.stock, order.shares) && res; + } + break; + case OrderTypes.LimitSell: + case OrderTypes.StopSell: + if (order.pos === PositionTypes.Long) { + res = sellStock(order.stock, order.shares) && res; + } else if (order.pos === PositionTypes.Short) { + res = sellShort(order.stock, order.shares) && res; + } + break; + } + if (res) { + //Remove order from order book + for (var i = 0; i < stockOrders.length; ++i) { + if (order == stockOrders[i]) { + stockOrders.splice(i, 1); + updateStockOrderList(order.stock); + return; + } + } + console.log("ERROR: Could not find the following Order in Order Book: "); + console.log(order); + } else { + console.log("Order failed to execute"); + } +} + +function Order(stock, shares, price, type, position) { + this.stock = stock; + this.shares = shares; + this.price = price; + this.type = type; + this.pos = position; +} + +Order.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Order", this); +} + +Order.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Order, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Order = Order; + +let StockMarket = {} //Full name to stock object +let StockSymbols = {} //Full name to symbol +let SymbolToStockMap = {}; //Symbol to Stock object + +function loadStockMarket(saveString) { + if (saveString === "") { + StockMarket = {}; + } else { + StockMarket = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"]); + } +} + +function initStockSymbols() { + //Stocks for companies at which you can work + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp] = "ECP"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp] = "MGCP"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries] = "BLD"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated] = "CLRK"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated] = "OMTK"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma] = "FSIG"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational] = "KGI"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies] = "FLCM"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies] = "STM"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm] = "DCOMM"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs] = "HLS"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife] = "VITA"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems] = "ICRS"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy] = "UNV"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp] = "AERO"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems] = "OMN"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems] = "SLRS"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals] = "GPH"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical] = "NVMD"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity] = "WDS"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp] = "LXO"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction] = "RHOC"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises] = "APHE"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities] = "SYSC"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek] = "CTK"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies] = "NTLK"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware] = "OMGA"; + StockSymbols[_Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff] = "FNS"; + + //Stocks for other companies + StockSymbols["Sigma Cosmetics"] = "SGC"; + StockSymbols["Joes Guns"] = "JGN"; + StockSymbols["Catalyst Ventures"] = "CTYS"; + StockSymbols["Microdyne Technologies"] = "MDYN"; + StockSymbols["Titan Laboratories"] = "TITN"; +} + +function initStockMarket() { + for (var stk in StockMarket) { + if (StockMarket.hasOwnProperty(stk)) { + delete StockMarket[stk]; + } + } + + var ecorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumECorp; + var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); + StockMarket[ecorp] = ecorpStk; + + var megacorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12MegaCorp; + var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.45, true, 19, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(25000, 33000)); + StockMarket[megacorp] = megacorpStk; + + var blade = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12BladeIndustries; + var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 22000)); + StockMarket[blade] = bladeStk; + + var clarke = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumClarkeIncorporated; + var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); + StockMarket[clarke] = clarkeStk; + + var omnitek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniTekIncorporated; + var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(35000, 40000)); + StockMarket[omnitek] = omnitekStk; + + var foursigma = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FourSigma; + var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.05, true, 17, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(60000, 70000)); + StockMarket[foursigma] = foursigmaStk; + + var kuaigong = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingKuaiGongInternational; + var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 24000)); + StockMarket[kuaigong] = kuaigongStk; + + var fulcrum = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumFulcrumTechnologies; + var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 16, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(30000, 35000)); + StockMarket[fulcrum] = fulcrumStk; + + var storm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaStormTechnologies; + var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(21000, 24000)); + StockMarket[storm] = stormStk; + + var defcomm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoDefComm; + var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); + StockMarket[defcomm] = defcommStk; + + var helios = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenHeliosLabs; + var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(12000, 16000)); + StockMarket[helios] = heliosStk; + + var vitalife = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoVitaLife; + var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 12000)); + StockMarket[vitalife] = vitalifeStk; + + var icarus = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12IcarusMicrosystems; + var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(16000, 20000)); + StockMarket[icarus] = icarusStk; + + var universalenergy = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12UniversalEnergy; + var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); + StockMarket[universalenergy] = universalenergyStk; + + var aerocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumAeroCorp; + var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(10000, 15000)); + StockMarket[aerocorp] = aerocorpStk; + + var omnia = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenOmniaCybersystems; + var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(9000, 12000)); + StockMarket[omnia] = omniaStk; + + var solaris = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].ChongqingSolarisSpaceSystems; + var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); + StockMarket[solaris] = solarisStk; + + var globalpharm = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].NewTokyoGlobalPharmaceuticals; + var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); + StockMarket[globalpharm] = globalpharmStk; + + var nova = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaNovaMedical; + var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(18000, 24000)); + StockMarket[nova] = novaStk; + + var watchdog = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumWatchdogSecurity; + var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 2.5, true, 1.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); + StockMarket[watchdog] = watchdogStk; + + var lexocorp = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenLexoCorp; + var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 6, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); + StockMarket[lexocorp] = lexocorpStk; + + var rho = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumRhoConstruction; + var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); + StockMarket[rho] = rhoStk; + + var alpha = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12AlphaEnterprises; + var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.9, true, 10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(5000, 7500)); + StockMarket[alpha] = alphaStk; + + var syscore = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenSysCoreSecurities; + var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.6, true, 3, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(4000, 7000)) + StockMarket[syscore] = syscoreStk; + + var computek = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].VolhavenCompuTek; + var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 4, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 5000)); + StockMarket[computek] = computekStk; + + var netlink = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].AevumNetLinkTechnologies; + var netlinkStk = new Stock(netlink, StockSymbols[netlink], 4.2, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 4000)); + StockMarket[netlink] = netlinkStk; + + var omega = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].IshimaOmegaSoftware; + var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(3000, 6000)); + StockMarket[omega] = omegaStk; + + var fns = _Location_js__WEBPACK_IMPORTED_MODULE_2__["Locations"].Sector12FoodNStuff; + var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(1000, 4000)); + StockMarket[fns] = fnsStk; + + var sigmacosm = "Sigma Cosmetics"; + var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 2.8, true, 0, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(2000, 3000)); + StockMarket[sigmacosm] = sigmacosmStk; + + var joesguns = "Joes Guns"; + var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 3.8, true, 1, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); + StockMarket[joesguns] = joesgunsStk; + + var catalyst = "Catalyst Ventures"; + var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.45, true, 13.5, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(500, 1000)); + StockMarket[catalyst] = catalystStk; + + var microdyne = "Microdyne Technologies"; + var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(20000, 25000)); + StockMarket[microdyne] = microdyneStk; + + var titanlabs = "Titan Laboratories"; + var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["getRandomInt"])(15000, 20000)); + StockMarket[titanlabs] = titanlabsStk; + + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; +} + +function initSymbolToStockMap() { + for (var name in StockSymbols) { + if (StockSymbols.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (stock == null) { + console.log("ERROR finding stock"); + continue; + } + var symbol = StockSymbols[name]; + SymbolToStockMap[symbol] = stock; + } + } +} + +function stockMarketCycle() { + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + var thresh = 0.6; + if (stock.b) {thresh = 0.4;} + if (Math.random() < thresh) { + stock.b = !stock.b; + } + } + } +} + +//Returns true if successful, false otherwise +function buyStock(stock, shares) { + if (stock == null || shares < 0 || isNaN(shares)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to buy stock. This may be a bug, contact developer"); + return false; + } + shares = Math.round(shares); + if (shares == 0) {return false;} + + var totalPrice = stock.price * shares; + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this. You need $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2).toString() + "."); + return false; + } + + var origTotal = stock.playerShares * stock.playerAvgPx; + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShares += shares; + stock.playerAvgPx = newTotal / stock.playerShares; + updateStockPlayerPosition(stock); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); + return true; +} + +//Returns true if successful and false otherwise +function sellStock(stock, shares) { + if (shares == 0) {return false;} + if (stock == null || shares < 0 || isNaN(shares)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell stock. This may be a bug, contact developer"); + return false; + } + shares = Math.round(shares); + if (shares > stock.playerShares) {shares = stock.playerShares;} + if (shares === 0) {return false;} + var gains = stock.price * shares - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(gains); + stock.playerShares -= shares; + if (stock.playerShares == 0) { + stock.playerAvgPx = 0; + } + updateStockPlayerPosition(stock); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + + "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(gains, 2)); + return true; +} + +//Returns true if successful and false otherwise +function shortStock(stock, shares, workerScript=null) { + var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); + if (stock == null || isNaN(shares) || shares < 0) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: shortStock() failed because of invalid arguments."); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to initiate a short position in a stock. This is probably " + + "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); + } + return false; + } + shares = Math.round(shares); + if (shares === 0) {return false;} + + var totalPrice = stock.price * shares; + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission)) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: shortStock() failed because you do not have " + + "money to purchase this short position. You need " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)')); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("You do not have enough money to purchase this short position. You need $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + "."); + } + + return false; + } + + var origTotal = stock.playerShortShares * stock.playerAvgShortPx; + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission); + var newTotal = origTotal + totalPrice; + stock.playerShortShares += shares; + stock.playerAvgShortPx = newTotal / stock.playerShortShares; + updateStockPlayerPosition(stock); + if (tixApi) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.shortStock == null) { + workerScript.scriptRef.log("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. Paid " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission).format('($0.000a)') + " in commission fees."); + } + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Bought a short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " in commission fees."); + } + return true; +} + +//Returns true if successful and false otherwise +function sellShort(stock, shares, workerScript=null) { + var tixApi = (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]); + if (stock == null || isNaN(shares) || shares < 0) { + if (tixApi) { + workerScript.scriptRef.log("ERROR: sellShort() failed because of invalid arguments."); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Failed to sell a short position in a stock. This is probably " + + "due to an invalid quantity. Otherwise, this may be a bug, so contact developer"); + } + return false; + } + shares = Math.round(shares); + if (shares > stock.playerShortShares) {shares = stock.playerShortShares;} + if (shares === 0) {return false;} + + var origCost = shares * stock.playerAvgShortPx; + var profit = ((stock.playerAvgShortPx - stock.price) * shares) - _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; + if (isNaN(profit)) {profit = 0;} + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].gainMoney(origCost + profit); + if (tixApi) { + workerScript.scriptRef.onlineMoneyMade += profit; + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].scriptProdSinceLastAug += profit; + } + + stock.playerShortShares -= shares; + if (stock.playerShortShares === 0) { + stock.playerAvgShortPx = 0; + } + updateStockPlayerPosition(stock); + if (tixApi) { + if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellShort == null) { + workerScript.scriptRef.log("Sold your short position of " + shares + " shares of " + stock.symbol + " at " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.price).format('($0.000a)') + " per share. After commissions, you gained " + + "a total of " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(origCost + profit).format('($0.000a)')); + } + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("Sold your short position of " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " + + "a total of $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(origCost + profit, 2)); + } + + return true; +} + +function updateStockPrices() { + var v = Math.random(); + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + var av = (v * stock.mv) / 100; + if (isNaN(av)) {av = .02;} + + var chc = 50; + if (stock.b) { + chc = (chc + stock.otlkMag)/100; + if (isNaN(chc)) {chc = 0.5;} + } else { + chc = (chc - stock.otlkMag)/100; + if (isNaN(chc)) {chc = 0.5;} + } + if (stock.price >= StockPriceCap) { + chc = -1; //Limit on stock price + stock.b = false; + } + + var c = Math.random(); + if (c < chc) { + stock.price *= (1 + av); + processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Short); + processOrders(stock, OrderTypes.LimitSell, PositionTypes.Long); + processOrders(stock, OrderTypes.StopBuy, PositionTypes.Long); + processOrders(stock, OrderTypes.StopSell, PositionTypes.Short); + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { + updateStockTicker(stock, true); + } + } else { + stock.price /= (1 + av); + processOrders(stock, OrderTypes.LimitBuy, PositionTypes.Long); + processOrders(stock, OrderTypes.LimitSell, PositionTypes.Short); + processOrders(stock, OrderTypes.StopBuy, PositionTypes.Short); + processOrders(stock, OrderTypes.StopSell, PositionTypes.Long); + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) { + updateStockTicker(stock, false); + } + } + + var otlkMagChange = stock.otlkMag * av; + if (stock.otlkMag <= 0.1) { + otlkMagChange = 1; + } + if (c < 0.5) { + stock.otlkMag += otlkMagChange; + } else { + stock.otlkMag -= otlkMagChange; + } + if (stock.otlkMag < 0) { + stock.otlkMag *= -1; + stock.b = !stock.b; + } + + } + } +} + +//Checks and triggers any orders for the specified stock +function processOrders(stock, orderType, posType) { + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + return; //Newly created, so no orders to process + } + var stockOrders = orderBook[stock.symbol]; + if (stockOrders == null || !(stockOrders.constructor === Array)) { + console.log("ERROR: Invalid Order book for " + stock.symbol + " in processOrders()"); + stockOrders = []; + return; + } + for (var i = 0; i < stockOrders.length; ++i) { + var order = stockOrders[i]; + if (order.type === orderType && order.pos === posType) { + switch(order.type) { + case OrderTypes.LimitBuy: + if (order.pos === PositionTypes.Long && stock.price <= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.LimitSell: + if (order.pos === PositionTypes.Long && stock.price >= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.StopBuy: + if (order.pos === PositionTypes.Long && stock.price >= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price <= order.price) { + executeOrder/*66*/(order); + } + break; + case OrderTypes.StopSell: + if (order.pos === PositionTypes.Long && stock.price <= order.price) { + executeOrder/*66*/(order); + } else if (order.pos === PositionTypes.Short && stock.price >= order.price) { + executeOrder/*66*/(order); + } + break; + default: + console.log("Invalid order type: " + order.type); + return; + } + } + } +} + +function setStockMarketContentCreated(b) { + stockMarketContentCreated = b; +} + +var stockMarketContentCreated = false; +var stockMarketPortfolioMode = false; +var COMM = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission; +function displayStockMarketContent() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = false;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess == null) {_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = false;} + + //Purchase WSE Account button + var wseAccountButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-account"); + wseAccountButton.innerText = "Buy WSE Account - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost, 2).toString(); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost)) { + wseAccountButton.setAttribute("class", "a-link-button"); + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount){ + wseAccountButton.innerText = "WSE Account - Purchased"; + wseAccountButton.setAttribute("class", "a-link-button-bought"); + } else { + wseAccountButton.setAttribute("class", "a-link-button-inactive"); + } + wseAccountButton.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount = true; + initStockMarket(); + initSymbolToStockMap(); + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].WSEAccountCost); + displayStockMarketContent(); + return false; + }); + + //Purchase TIX API Access account + var tixApiAccessButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-buy-tix-api"); + tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost, 2).toString(); + if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.gte(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost)) { + tixApiAccessButton.setAttribute("class", "a-link-button"); + } else if(_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess) { + tixApiAccessButton.innerText = "Trade Information eXchange (TIX) API Access - Purchased" + tixApiAccessButton.setAttribute("class", "a-link-button-bought"); + } else { + tixApiAccessButton.setAttribute("class", "a-link-button-inactive"); + } + tixApiAccessButton.addEventListener("click", function() { + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasTixApiAccess = true; + _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].TIXAPICost); + displayStockMarketContent(); + return false; + }); + + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} + + if (!_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { + stockMarketContentCreated = false; + while (stockList.firstChild) { + stockList.removeChild(stockList.firstChild); + } + return; + } + + //Create stock market content if you have an account + if (!stockMarketContentCreated && _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { + console.log("Creating Stock Market UI"); + document.getElementById("stock-market-commission").innerHTML = + "Commission Fees: Every transaction you make has a $" + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].StockMarketCommission, 2) + " commission fee.

" + + "WARNING: When you reset after installing Augmentations, the Stock Market is reset. " + + "This means all your positions are lost, so make sure to sell your stocks before installing " + + "Augmentations!"; + + var investopediaButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-investopedia"); + investopediaButton.addEventListener("click", function() { + var txt = "When making a transaction on the stock market, there are two " + + "types of positions: Long and Short. A Long position is the typical " + + "scenario where you buy a stock and earn a profit if the price of that " + + "stock increases. Meanwhile, a Short position is the exact opposite. " + + "In a Short position you purchase shares of a stock and earn a profit " + + "if the price of that stock decreases. This is also called 'shorting' a stock.

" + + "NOTE: Shorting stocks is not available immediately, and must be unlocked later on in the game.

" + + "There are three different types of orders you can make to buy or sell " + + "stocks on the exchange: Market Order, Limit Order, and Stop Order. " + + "Note that Limit Orders and Stop Orders are not available immediately, and must be unlocked " + + "later on in the game.

" + + "When you place a Market Order to buy or sell a stock, the order executes " + + "immediately at whatever the current price of the stock is. For example " + + "if you choose to short a stock with 5000 shares using a Market Order, " + + "you immediately purchase those 5000 shares in a Short position at whatever " + + "the current market price is for that stock.

" + + "A Limit Order is an order that only executes under certain conditions. " + + "A Limit Order is used to buy or sell a stock at a specified price or better. " + + "For example, lets say you purchased a Long position of 100 shares of some stock " + + "at a price of $10 per share. You can place a Limit Order to sell those 100 shares " + + "at $50 or better. The Limit Order will execute when the price of the stock reaches a " + + "value of $50 or higher.

" + + "A Stop Order is the opposite of a Limit Order. It is used to buy or sell a stock " + + "at a specified price (before the price gets 'worse'). For example, lets say you purchased " + + "a Short position of 100 shares of some stock at a price of $100 per share. " + + "The current price of the stock is $80 (a profit of $20 per share). You can place a " + + "Stop Order to sell the Short position if the stock's price reaches $90 or higher. " + + "This can be used to lock in your profits and limit any losses.

" + + "Here is a summary of how each order works and when they execute:

" + + "In a LONG Position:

" + + "A Limit Order to buy will execute if the stock's price <= order's price
" + + "A Limit Order to sell will execute if the stock's price >= order's price
" + + "A Stop Order to buy will execute if the stock's price >= order's price
" + + "A Stop Order to sell will execute if the stock's price <= order's price

" + + "In a SHORT Position:

" + + "A Limit Order to buy will execute if the stock's price >= order's price
" + + "A Limit Order to sell will execute if the stock's price <= order's price
" + + "A Stop Order to buy will execute if the stock's price <= order's price
" + + "A Stop Order to sell will execute if the stock's price >= order's price."; + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])(txt); + return false; + }); + + //Switch to Portfolio Mode Button + var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + + "Displays only the stocks for which you have shares or orders"; + modeBtn.addEventListener("click", switchToPortfolioMode); + } + + //Expand/Collapse tickers buttons + var expandBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-expand-tickers"), + collapseBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-collapse-tickers"), + stockList = document.getElementById("stock-market-list"); + if (expandBtn) { + expandBtn.addEventListener("click", ()=>{ + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + for (var i = 0; i < tickerHdrs.length; ++i) { + if (!tickerHdrs[i].classList.contains("active")) { + tickerHdrs[i].click(); + } + } + }); + } + if (collapseBtn) { + collapseBtn.addEventListener("click",()=>{ + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + for (var i = 0; i < tickerHdrs.length; ++i) { + if (tickerHdrs[i].classList.contains("active")) { + tickerHdrs[i].click(); + } + } + }); + } + + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); //Clicking headers opens/closes panels + stockMarketContentCreated = true; + } + + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].hasWseAccount) { + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + updateStockTicker(stock, null); + updateStockOrderList(stock); + } + } + } +} + +//Displays only stocks you have position/order in +function switchToPortfolioMode() { + stockMarketPortfolioMode = true; + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} + var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'All stocks' Mode" + + "Displays all stocks on the WSE"; + modeBtn.addEventListener("click", switchToDisplayAllMode); + } + while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} + + //Get Order book (create it if it hasn't been created) + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + var orders = {}; + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} + orders[stock.symbol] = []; + } + } + StockMarket["Orders"] = orders; + } + + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + var stockOrders = orderBook[stock.symbol]; + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + stockOrders.length === 0) {continue;} + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); +} + +//Displays all stocks +function switchToDisplayAllMode() { + stockMarketPortfolioMode = false; + var stockList = document.getElementById("stock-market-list"); + if (stockList == null) {return;} + var modeBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["clearEventListeners"])("stock-market-mode"); + if (modeBtn) { + modeBtn.innerHTML = "Switch to 'Portfolio' Mode" + + "Displays only the stocks for which you have shares or orders"; + modeBtn.addEventListener("click", switchToPortfolioMode); + } + while(stockList.firstChild) {stockList.removeChild(stockList.firstChild);} + for (var name in StockMarket) { + if (StockMarket.hasOwnProperty(name)) { + var stock = StockMarket[name]; + if (!(stock instanceof Stock)) {continue;} //orders property is an array + createStockTicker(stock); + } + } + setStockTickerClickHandlers(); +} + +function createStockTicker(stock) { + if (!(stock instanceof Stock)) { + console.log("Invalid stock in createStockSticker()"); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + var li = document.createElement("li"), hdr = document.createElement("button"); + hdr.classList.add("accordion-header"); + hdr.setAttribute("id", tickerId + "-hdr"); + hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + stock.price; + + //Div for entire panel + var stockDiv = document.createElement("div"); + stockDiv.classList.add("accordion-panel"); + stockDiv.setAttribute("id", tickerId + "-panel"); + + /* Create panel DOM */ + var qtyInput = document.createElement("input"), + longShortSelect = document.createElement("select"), + orderTypeSelect = document.createElement("select"), + buyButton = document.createElement("span"), + sellButton = document.createElement("span"), + buyMaxButton = document.createElement("span"), + sellAllButton = document.createElement("span"), + positionTxt = document.createElement("p"), + orderList = document.createElement("ul"); + + qtyInput.classList.add("stock-market-input"); + qtyInput.placeholder = "Quantity (Shares)"; + qtyInput.setAttribute("id", tickerId + "-qty-input"); + qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " + + " || (4734 && event.keyCode<40) " + + " || (event.keyCode==46) )"); + + longShortSelect.classList.add("stock-market-input"); + longShortSelect.setAttribute("id", tickerId + "-pos-selector"); + var longOpt = document.createElement("option"); + longOpt.text = "Long"; + longShortSelect.add(longOpt); + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 2)) { + var shortOpt = document.createElement("option"); + shortOpt.text = "Short"; + longShortSelect.add(shortOpt); + } + + orderTypeSelect.classList.add("stock-market-input"); + orderTypeSelect.setAttribute("id", tickerId + "-order-selector"); + var marketOpt = document.createElement("option"); + marketOpt.text = "Market Order"; + orderTypeSelect.add(marketOpt); + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 3)) { + var limitOpt = document.createElement("option"); + limitOpt.text = "Limit Order"; + orderTypeSelect.add(limitOpt); + var stopOpt = document.createElement("option"); + stopOpt.text = "Stop Order"; + orderTypeSelect.add(stopOpt); + } + + buyButton.classList.add("stock-market-input"); + buyButton.classList.add("a-link-button"); + buyButton.innerHTML = "Buy"; + buyButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var shares = Number(document.getElementById(tickerId + "-qty-input").value); + if (isNaN(shares)) {return false;} + switch (ordType) { + case "Market Order": + pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), + noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); + yesBtn.innerText = "Place Buy " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitBuy; + } else { + type = OrderTypes.StopBuy; + } + placeOrder(stock, shares, price, type, pos); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + }); + noBtn.addEventListener("click", ()=>{ + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + }); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + sellButton.classList.add("stock-market-input"); + sellButton.classList.add("a-link-button"); + sellButton.innerHTML = "Sell"; + sellButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var shares = Number(document.getElementById(tickerId + "-qty-input").value); + if (isNaN(shares)) {return false;} + switch (ordType) { + case "Market Order": + pos === PositionTypes.Long ? sellStock(stock, shares) : sellShort(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), + noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); + yesBtn.innerText = "Place Sell " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitSell; + } else { + type = OrderTypes.StopSell; + } + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + placeOrder(stock, shares, price, type, pos); + }); + noBtn.addEventListener("click", ()=>{ + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + }); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + buyMaxButton.classList.add("stock-market-input"); + buyMaxButton.classList.add("a-link-button"); + buyMaxButton.innerHTML = "Buy MAX"; + buyMaxButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + var money = _Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].money.toNumber(); + switch (ordType) { + case "Market Order": + var shares = Math.floor((money - COMM) / stock.price); + pos === PositionTypes.Long ? buyStock(stock, shares) : shortStock(stock, shares, null); + break; + case "Limit Order": + case "Stop Order": + var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetYesButton"])(), + noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetNoButton"])(); + yesBtn.innerText = "Place Buy " + ordType; + noBtn.innerText = "Cancel Order"; + yesBtn.addEventListener("click", ()=>{ + var price = Number(Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxGetInput"])()), type; + if (ordType === "Limit Order") { + type = OrderTypes.LimitBuy; + } else { + type = OrderTypes.StopBuy; + } + var shares = Math.floor((money-COMM) / price); + placeOrder(stock, shares, price, type, pos); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + }); + noBtn.addEventListener("click", ()=>{ + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxClose"])(); + }); + Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_11__["yesNoTxtInpBoxCreate"])("Enter the price for your " + ordType); + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + sellAllButton.classList.add("stock-market-input"); + sellAllButton.classList.add("a-link-button"); + sellAllButton.innerHTML = "Sell ALL"; + sellAllButton.addEventListener("click", ()=>{ + var pos = longShortSelect.options[longShortSelect.selectedIndex].text; + pos === "Long" ? pos = PositionTypes.Long : pos = PositionTypes.Short; + var ordType = orderTypeSelect.options[orderTypeSelect.selectedIndex].text; + switch (ordType) { + case "Market Order": + if (pos === PositionTypes.Long) { + var shares = stock.playerShares; + sellStock(stock, shares); + } else { + var shares = stock.playerShortShares; + sellShort(stock, shares, null); + } + break; + case "Limit Order": + case "Stop Order": + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__["dialogBoxCreate"])("ERROR: 'Sell All' only works for Market Orders") + break; + default: + console.log("ERROR: Invalid order type"); + break; + } + return false; + }); + + positionTxt.setAttribute("id", tickerId + "-position-text"); + positionTxt.classList.add("stock-market-position-text"); + stock.posTxtEl = positionTxt; + + orderList.setAttribute("id", tickerId + "-order-list"); + orderList.classList.add("stock-market-order-list"); + + stockDiv.appendChild(qtyInput); + stockDiv.appendChild(longShortSelect); + stockDiv.appendChild(orderTypeSelect); + stockDiv.appendChild(buyButton); + stockDiv.appendChild(sellButton); + stockDiv.appendChild(buyMaxButton); + stockDiv.appendChild(sellAllButton); + stockDiv.appendChild(positionTxt); + stockDiv.appendChild(orderList); + + li.appendChild(hdr); + li.appendChild(stockDiv); + document.getElementById("stock-market-list").appendChild(li); + + updateStockTicker(stock, true); + updateStockPlayerPosition(stock); + updateStockOrderList(stock); +} + +function setStockTickerClickHandlers() { + var stockList = document.getElementById("stock-market-list"); + var tickerHdrs = stockList.getElementsByClassName("accordion-header"); + if (tickerHdrs == null) { + console.log("ERROR: Could not find header elements for stock tickers"); + return; + } + for (var i = 0; i < tickerHdrs.length; ++i) { + tickerHdrs[i].onclick = function() { + this.classList.toggle("active"); + + var panel = this.nextElementSibling; + if (panel.style.display === "block") { + panel.style.display = "none"; + } else { + panel.style.display = "block"; + } + } + } +} + +//'increase' argument is a boolean indicating whether the price increased or decreased +function updateStockTicker(stock, increase) { + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} + if (!(stock instanceof Stock)) { + console.log("Invalid stock in updateStockTicker():"); + console.log(stock); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + + if (stock.playerShares > 0 || stock.playerShortShares > 0) { + updateStockPlayerPosition(stock); + } + + var hdr = document.getElementById(tickerId + "-hdr"); + + if (hdr == null) { + if (!stockMarketPortfolioMode) {console.log("ERROR: Couldn't find ticker element for stock: " + stock.symbol);} + return; + } + hdr.innerHTML = stock.name + " - " + stock.symbol + " - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2); + if (increase != null) { + increase ? hdr.style.color = "#66ff33" : hdr.style.color = "red"; + } +} + +function updateStockPlayerPosition(stock) { + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} + if (!(stock instanceof Stock)) { + console.log("Invalid stock in updateStockPlayerPosition():"); + console.log(stock); + return; + } + var tickerId = "stock-market-ticker-" + stock.symbol; + + if (stockMarketPortfolioMode) { + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && + StockMarket["Orders"][stock.symbol].length === 0) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr"); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel"); + return; + } else { + //If the ticker hasn't been created, create it (handles updating) + //If it has been created, continue normally + if (document.getElementById(tickerId + "-hdr") == null) { + createStockTicker(stock); + setStockTickerClickHandlers(); + return; + } + } + } + + if (!(stock.posTxtEl instanceof Element)) { + stock.posTxtEl = document.getElementById(tickerId + "-position-text"); + } + if (stock.posTxtEl == null) { + console.log("ERROR: Could not find stock position element for: " + stock.symbol); + return; + } + + //Calculate returns + var totalCost = stock.playerShares * stock.playerAvgPx, + gains = (stock.price - stock.playerAvgPx) * stock.playerShares, + percentageGains = gains / totalCost; + if (isNaN(percentageGains)) {percentageGains = 0;} + + var shortTotalCost = stock.playerShortShares * stock.playerAvgShortPx, + shortGains = (stock.playerAvgShortPx - stock.price) * stock.playerShortShares, + shortPercentageGains = shortGains/ shortTotalCost; + if (isNaN(shortPercentageGains)) {shortPercentageGains = 0;} + + stock.posTxtEl.innerHTML = + "

Long Position: " + + "Shares in the long position will increase " + + "in value if the price of the corresponding stock increases

" + + "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShares, 0) + + "
Average Price: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgPx).format('$0.000a') + + " (Total Cost: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(totalCost).format('$0.000a') + ")" + + "
Profit: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(gains).format('$0.000a') + + " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(percentageGains*100, 2) + "%)

"; + if (_Player_js__WEBPACK_IMPORTED_MODULE_5__["Player"].bitNodeN === 8 || (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["hasWallStreetSF"] && _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_3__["wallStreetSFLvl"] >= 2)) { + stock.posTxtEl.innerHTML += + "

Short Position: " + + "Shares in short position will increase " + + "in value if the price of the corresponding stock decreases

" + + "
Shares: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.playerShortShares, 0) + + "
Average Price: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(stock.playerAvgShortPx).format('$0.000a') + + " (Total Cost: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(shortTotalCost).format('$0.000a') + ")" + + "
Profit: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_9___default()(shortGains).format('$0.000a') + + " (" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shortPercentageGains*100, 2) + "%)" + + "

Orders:

"; + } + +} + +function updateStockOrderList(stock) { + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.StockMarket) {return;} + var tickerId = "stock-market-ticker-" + stock.symbol; + var orderList = document.getElementById(tickerId + "-order-list"); + if (orderList == null) { + if (!stockMarketPortfolioMode) {console.log("ERROR: Could not find order list for " + stock.symbol);} + return; + } + + var orderBook = StockMarket["Orders"]; + if (orderBook == null) { + console.log("ERROR: Could not find order book in stock market"); + return; + } + var stockOrders = orderBook[stock.symbol]; + if (stockOrders == null) { + console.log("ERROR: Could not find orders for: " + stock.symbol); + return; + } + + if (stockMarketPortfolioMode) { + if (stock.playerShares === 0 && stock.playerShortShares === 0 && + StockMarket["Orders"] && StockMarket["Orders"][stock.symbol] && + StockMarket["Orders"][stock.symbol].length === 0) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-hdr"); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__["removeElementById"])(tickerId + "-panel"); + return; + } else { + //If the ticker hasn't been created, create it (handles updating) + //If it has been created, continue normally + if (document.getElementById(tickerId + "-hdr") == null) { + createStockTicker(stock); + setStockTickerClickHandlers(); + return; + } + } + } + + //Remove everything from list + while (orderList.firstChild) { + orderList.removeChild(orderList.firstChild); + } + + for (var i = 0; i < stockOrders.length; ++i) { + (function() { + var order = stockOrders[i]; + var li = document.createElement("li"); + li.style.padding = "4px"; + var posText = (order.pos === PositionTypes.Long ? "Long Position" : "Short Position"); + li.style.color = "white"; + li.innerText = order.type + " - " + posText + " - " + + order.shares + " @ $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(order.price, 2); + + var cancelButton = document.createElement("span"); + cancelButton.classList.add("stock-market-order-cancel-btn"); + cancelButton.classList.add("a-link-button"); + cancelButton.innerHTML = "Cancel Order"; + cancelButton.addEventListener("click", function() { + cancelOrder({order: order}, null); + return false; + }); + li.appendChild(cancelButton); + orderList.appendChild(li); + }()); + + } +} + + + + +/***/ }), +/* 30 */ /*!**********************!*\ !*** ./src/Fconf.js ***! \**********************/ @@ -34591,7 +29031,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createFconf", function() { return createFconf; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFconfSettings", function() { return parseFconfSettings; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadFconf", function() { return loadFconf; }); -/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn.js */ 36); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/acorn.js */ 32); /* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__); @@ -34723,27 +29163,40 @@ function loadFconf(saveString) { /***/ }), -/* 34 */ -/*!*************************!*\ - !*** ./src/Missions.js ***! - \*************************/ +/* 31 */ +/*!***********************************!*\ + !*** ./src/NetscriptEvaluator.js ***! + \***********************************/ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HackingMission", function() { return HackingMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inMission", function() { return inMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setInMission", function() { return setInMission; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currMission", function() { return currMission; }); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! jsplumb */ 197); -/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_7__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeRuntimeRejectMsg", function() { return makeRuntimeRejectMsg; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "netscriptDelay", function() { return netscriptDelay; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "runScriptFromScript", function() { return runScriptFromScript; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingChance", function() { return scriptCalculateHackingChance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateHackingTime", function() { return scriptCalculateHackingTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateExpGain", function() { return scriptCalculateExpGain; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculatePercentMoneyHacked", function() { return scriptCalculatePercentMoneyHacked; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateGrowTime", function() { return scriptCalculateGrowTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptCalculateWeakenTime", function() { return scriptCalculateWeakenTime; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluate", function() { return evaluate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isScriptErrorMessage", function() { return isScriptErrorMessage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "killNetscriptDelay", function() { return killNetscriptDelay; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "evaluateImport", function() { return evaluateImport; }); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 80); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/acorn.js */ 32); +/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); @@ -34753,1755 +29206,927 @@ __webpack_require__.r(__webpack_exports__); -let inMission = false; //Flag to denote whether a mission is running -let currMission = null; -function setInMission(bool, mission) { - inMission = bool; - if (bool) { - currMission = mission; - } else { - currMission = null; - } -} -//Keyboard shortcuts -$(document).keydown(function(e) { - if (inMission && currMission && currMission.selectedNode.length != 0) { - switch (e.keyCode) { - case 65: //a for Attack - currMission.actionButtons[0].click(); - break; - case 83: //s for Scan - currMission.actionButtons[1].click(); - break; - case 87: //w for Weaken - currMission.actionButtons[2].click(); - break; - case 70: //f for Fortify - currMission.actionButtons[3].click(); - break; - case 82: //r for Overflow - currMission.actionButtons[4].click(); - break; - case 68: //d for Detach connection - currMission.actionButtons[5].click(); - break; - default: - break; - } - } + + + + +var Promise = __webpack_require__(/*! bluebird */ 181); + +Promise.config({ + warnings: false, + longStackTraces: false, + cancellation: true, + monitoring: false }); - -let NodeTypes = { - Core: "CPU Core Node", //All actions available - Firewall: "Firewall Node", //No actions available - Database: "Database Node", //No actions available - Spam: "Spam Node", //No actions Available - Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow - Shield: "Shield Node" //Can Fortify -} - -let NodeActions = { - Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def - Scan: "Scanning", //-Def for target, affected by attack and hacking level - Weaken: "Weakening", //-Attack for target, affected by attack and hacking level - Fortify: "Fortifying", //+Defense for Node, affected by hacking level - Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level -} - -function Node(type, stats) { - this.type = type; - this.atk = stats.atk ? stats.atk : 0; - this.def = stats.def ? stats.def : 0; - this.hp = stats.hp ? stats.hp : 0; - this.maxhp = this.hp; - this.plyrCtrl = false; - this.enmyCtrl = false; - this.pos = [0, 0]; //x, y - this.el = null; //Holds the Node's DOM element - this.action = null; - this.targetedCount = 0; //Count of how many connections this node is the target of - - //Holds the JsPlumb Connection object for this Node, - //where this Node is the Source (since each Node - //can only have 1 outgoing Connection) - this.conn = null; -} - -Node.prototype.setPosition = function(x, y) { - this.pos = [x, y]; -} - -Node.prototype.setControlledByPlayer = function() { - this.plyrCtrl = true; - this.enmyCtrl = false; - if (this.el) { - this.el.classList.remove("hack-mission-enemy-node"); - this.el.classList.add("hack-mission-player-node"); - } -} - -Node.prototype.setControlledByEnemy = function() { - this.plyrCtrl = false; - this.enmyCtrl = true; - if (this.el) { - this.el.classList.remove("hack-mission-player-node"); - this.el.classList.add("hack-mission-enemy-node"); - } -} - -//Sets this node to be the active node -Node.prototype.select = function(actionButtons) { - if (this.enmyCtrl) {return;} - this.el.classList.add("hack-mission-player-node-active"); - - //Make all buttons inactive - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button"); - actionButtons[i].classList.add("a-link-button-inactive"); - } - - switch(this.type) { - case NodeTypes.Core: - //All buttons active - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button-inactive"); - actionButtons[i].classList.add("a-link-button"); - } - break; - case NodeTypes.Transfer: - actionButtons[1].classList.remove("a-link-button-inactive"); - actionButtons[1].classList.add("a-link-button"); - actionButtons[2].classList.remove("a-link-button-inactive"); - actionButtons[2].classList.add("a-link-button"); - actionButtons[3].classList.remove("a-link-button-inactive"); - actionButtons[3].classList.add("a-link-button"); - actionButtons[4].classList.remove("a-link-button-inactive"); - actionButtons[4].classList.add("a-link-button"); - actionButtons[5].classList.remove("a-link-button-inactive"); - actionButtons[5].classList.add("a-link-button"); - break; - case NodeTypes.Shield: - case NodeTypes.Firewall: - actionButtons[3].classList.remove("a-link-button-inactive"); - actionButtons[3].classList.add("a-link-button"); - break; - default: - break; - } -} - -Node.prototype.deselect = function(actionButtons) { - this.el.classList.remove("hack-mission-player-node-active"); - for (var i = 0; i < actionButtons.length; ++i) { - actionButtons[i].classList.remove("a-link-button"); - actionButtons[i].classList.add("a-link-button-inactive"); - } -} - - -Node.prototype.untarget = function() { - if (this.targetedCount === 0) { - console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count"); - return; - } - --this.targetedCount; -} - -//Hacking mission instance -//Takes in the reputation of the Faction for which the mission is -//being conducted -function HackingMission(rep, fac) { - this.faction = fac; - - this.started = false; - this.time = 180000; //5 minutes to start, milliseconds - - this.playerCores = []; - this.playerNodes = []; //Non-core nodes - this.playerAtk = 0; - this.playerDef = 0; - - this.enemyCores = []; - this.enemyDatabases = []; - this.enemyNodes = []; //Non-core nodes - this.enemyAtk = 0; - this.enemyDef = 0; - - this.miscNodes = []; - - this.selectedNode = []; //Which of the player's nodes are currently selected - - this.actionButtons = []; //DOM buttons for actions - - this.availablePositions = []; - for (var r = 0; r < 8; ++r) { - for (var c = 0; c < 8; ++c) { - this.availablePositions.push([r, c]); +/* Evaluator + * Evaluates/Interprets the Abstract Syntax Tree generated by Acorns parser + * + * Returns a promise + */ +function evaluate(exp, workerScript) { + return Promise.delay(_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + if (exp == null) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression", exp)); } - } - - this.map = []; - for (var i = 0; i < 8; ++i) { - this.map.push([null, null, null, null, null, null, null, null]); - } - - this.jsplumbinstance = null; - - this.difficulty = rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1; - console.log("difficulty: " + this.difficulty); - this.reward = 250 + (rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion); -} - -HackingMission.prototype.init = function() { - //Create Header DOM - this.createPageDom(); - - //Create player starting nodes - var home = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer() - for (var i = 0; i < home.cpuCores; ++i) { - var stats = { - atk: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5) + 30, - def: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20), - hp: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4), - }; - this.playerCores.push(new Node(NodeTypes.Core, stats)); - this.playerCores[i].setControlledByPlayer(); - this.setNodePosition(this.playerCores[i], i, 0); - this.removeAvailablePosition(i, 0); - } - - //Randomly generate enemy nodes (CPU and Firewall) based on difficulty - var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4))); - var numFirewalls = Math.min(20, - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1)); - var numDatabases = Math.min(10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1)); - var totalNodes = numNodes + numFirewalls + numDatabases; - var xlimit = 7 - Math.floor(totalNodes / 8); - var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.8 + (this.difficulty / 5), 10); - for (var i = 0; i < numNodes; ++i) { - var stats = { - atk: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(80, 86), - def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(5, 10), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 230) - } - this.enemyCores.push(new Node(NodeTypes.Core, stats)); - this.enemyCores[i].setControlledByEnemy(); - this.setNodeRandomPosition(this.enemyCores[i], xlimit); - } - for (var i = 0; i < numFirewalls; ++i) { - var stats = { - atk: 0, - def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(10, 20), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(275, 300) - } - this.enemyNodes.push(new Node(NodeTypes.Firewall, stats)); - this.enemyNodes[i].setControlledByEnemy(); - this.setNodeRandomPosition(this.enemyNodes[i], xlimit); - } - for (var i = 0; i < numDatabases; ++i) { - var stats = { - atk: 0, - def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 55), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 275) - } - var node = new Node(NodeTypes.Database, stats); - node.setControlledByEnemy(); - this.setNodeRandomPosition(node, xlimit); - this.enemyDatabases.push(node); - } - this.calculateDefenses(); - this.calculateAttacks(); - this.createMap(); -} - -HackingMission.prototype.createPageDom = function() { - var container = document.getElementById("mission-container"); - - var favorMult = 1 + (this.faction.favor / 100); - var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; - var headerText = document.createElement("p"); - headerText.innerHTML = "You are about to start a hacking mission! You will gain " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name + - " if you win. For more information " + - "about how hacking missions work, click one of the guide links " + - "below (one opens up an in-game guide and the other opens up " + - "the guide from the wiki). Click the 'Start' button to begin."; - headerText.style.display = "block"; - headerText.classList.add("hack-mission-header-element"); - headerText.style.width = "80%"; - - var inGameGuideBtn = document.createElement("a"); - inGameGuideBtn.innerText = "How to Play"; - inGameGuideBtn.classList.add("a-link-button"); - inGameGuideBtn.style.display = "inline-block"; - inGameGuideBtn.classList.add("hack-mission-header-element"); - inGameGuideBtn.addEventListener("click", function() { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay); - return false; - }); - - var wikiGuideBtn = document.createElement("a"); - wikiGuideBtn.innerText = "Wiki Guide"; - wikiGuideBtn.classList.add("a-link-button"); - wikiGuideBtn.style.display = "inline-block"; - wikiGuideBtn.classList.add("hack-mission-header-element"); - wikiGuideBtn.target = "_blank"; - //TODO Add link to wiki page wikiGuideBtn.href = - - - //Start button will get replaced with forfeit when game is started - var startBtn = document.createElement("a"); - startBtn.innerHTML = "Start"; - startBtn.setAttribute("id", "hack-mission-start-btn"); - startBtn.classList.add("a-link-button"); - startBtn.classList.add("hack-mission-header-element"); - startBtn.style.display = "inline-block"; - startBtn.addEventListener("click", ()=>{ - this.start(); - return false; - }); - - var forfeitMission = document.createElement("a"); - forfeitMission.innerHTML = "Forfeit Mission (Exit)"; - forfeitMission.classList.add("a-link-button"); - forfeitMission.classList.add("hack-mission-header-element"); - forfeitMission.style.display = "inline-block"; - forfeitMission.addEventListener("click", ()=> { - this.finishMission(false); - return false; - }); - - var timer = document.createElement("p"); - timer.setAttribute("id", "hacking-mission-timer"); - timer.style.display = "inline-block"; - timer.style.margin = "6px"; - - //Create Action Buttons (Attack/Scan/Weaken/ etc...) - var actionsContainer = document.createElement("span"); - actionsContainer.style.display = "block"; - actionsContainer.classList.add("hack-mission-action-buttons-container"); - for (var i = 0; i < 6; ++i) { - this.actionButtons.push(document.createElement("a")); - this.actionButtons[i].style.display = "inline-block"; - this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start - this.actionButtons[i].classList.add("tooltip"); //Disabled at start - this.actionButtons[i].classList.add("hack-mission-header-element"); - actionsContainer.appendChild(this.actionButtons[i]); - } - this.actionButtons[0].innerText = "Attack(a)"; - var atkTooltip = document.createElement("span"); - atkTooltip.classList.add("tooltiptexthigh"); - atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[0].appendChild(atkTooltip); - this.actionButtons[1].innerText = "Scan(s)"; - var scanTooltip = document.createElement("span"); - scanTooltip.classList.add("tooltiptexthigh"); - scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[1].appendChild(scanTooltip); - this.actionButtons[2].innerText = "Weaken(w)"; - var WeakenTooltip = document.createElement("span"); - WeakenTooltip.classList.add("tooltiptexthigh"); - WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " + - "this node's Attack level, your hacking level, and the opponent's defense level."; - this.actionButtons[2].appendChild(WeakenTooltip); - this.actionButtons[3].innerText = "Fortify(f)"; - var fortifyTooltip = document.createElement("span"); - fortifyTooltip.classList.add("tooltiptexthigh"); - fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " + - "your hacking level"; - this.actionButtons[3].appendChild(fortifyTooltip); - this.actionButtons[4].innerText = "Overflow(r)"; - var overflowTooltip = document.createElement("span"); - overflowTooltip.classList.add("tooltiptexthigh"); - overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " + - "of this depends on your hacking level."; - this.actionButtons[4].appendChild(overflowTooltip); - this.actionButtons[5].innerText = "Drop Connection(d)"; - var dropconnTooltip = document.createElement("span"); - dropconnTooltip.classList.add("tooltiptexthigh"); - dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " + - "also be done by simply clicking the white connection line."; - this.actionButtons[5].appendChild(dropconnTooltip); - - //Player/enemy defense displays will be in action container - var playerStats = document.createElement("p"); - var enemyStats = document.createElement("p"); - playerStats.style.display = "inline-block"; - enemyStats.style.display = "inline-block"; - playerStats.style.color = "#00ccff"; - enemyStats.style.color = "red"; - playerStats.style.margin = "4px"; - enemyStats.style.margin = "4px"; - playerStats.setAttribute("id", "hacking-mission-player-stats"); - enemyStats.setAttribute("id", "hacking-mission-enemy-stats"); - actionsContainer.appendChild(playerStats); - actionsContainer.appendChild(enemyStats); - - //Set Action Button event listeners - this.actionButtons[0].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - if (this.selectedNode[0].type !== NodeTypes.Core) {return;} - this.setActionButtonsActive(this.selectedNode[0].type); - this.setActionButton(NodeActions.Attack, false); //Set attack button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Attack; - }); - }); - - this.actionButtons[1].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Scan, false); //Set scan button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Scan; - }); - }); - - this.actionButtons[2].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Weaken; - }); - }); - - this.actionButtons[3].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - this.setActionButtonsActive(this.selectedNode[0].type); - this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Fortify; - }); - }); - - this.actionButtons[4].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - var nodeType = this.selectedNode[0].type; - if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} - this.setActionButtonsActive(nodeType); - this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive - this.selectedNode.forEach(function(node){ - node.action = NodeActions.Overflow; - }); - }); - - this.actionButtons[5].addEventListener("click", ()=>{ - if (!(this.selectedNode.length > 0)) { - console.log("ERR: Pressing Action button without selected node"); - return; - } - this.selectedNode.forEach(function(node){ - if (node.conn) { - var endpoints = node.conn.endpoints; - endpoints[0].detachFrom(endpoints[1]); - } - node.action = NodeActions.Fortify; - }); - // if (this.selectedNode.conn) { - // var endpoints = this.selectedNode.conn.endpoints; - // endpoints[0].detachFrom(endpoints[1]); - // } - }) - - var timeDisplay = document.createElement("p"); - - container.appendChild(headerText); - container.appendChild(inGameGuideBtn); - container.appendChild(wikiGuideBtn); - container.appendChild(startBtn); - container.appendChild(forfeitMission); - container.appendChild(timer); - container.appendChild(actionsContainer); - container.appendChild(timeDisplay); -} - -HackingMission.prototype.setActionButtonsInactive = function() { - for (var i = 0; i < this.actionButtons.length; ++i) { - this.actionButtons[i].classList.remove("a-link-button"); - this.actionButtons[i].classList.add("a-link-button-inactive"); - } -} - -HackingMission.prototype.setActionButtonsActive = function(nodeType=null) { - for (var i = 0; i < this.actionButtons.length; ++i) { - this.actionButtons[i].classList.add("a-link-button"); - this.actionButtons[i].classList.remove("a-link-button-inactive"); - } - - //For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled - //0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn - if (nodeType) { - switch (nodeType) { - case NodeTypes.Firewall: - case NodeTypes.Shield: - this.actionButtons[0].classList.remove("a-link-button"); - this.actionButtons[0].classList.add("a-link-button-inactive"); - this.actionButtons[1].classList.remove("a-link-button"); - this.actionButtons[1].classList.add("a-link-button-inactive"); - this.actionButtons[2].classList.remove("a-link-button"); - this.actionButtons[2].classList.add("a-link-button-inactive"); - this.actionButtons[4].classList.remove("a-link-button"); - this.actionButtons[4].classList.add("a-link-button-inactive"); - this.actionButtons[5].classList.remove("a-link-button"); - this.actionButtons[5].classList.add("a-link-button-inactive"); - break; - case NodeTypes.Transfer: - this.actionButtons[0].classList.remove("a-link-button"); - this.actionButtons[0].classList.add("a-link-button-inactive"); - break; - default: - break; - } - } -} - -//True for active, false for inactive -HackingMission.prototype.setActionButton = function(i, active=true) { - if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(i)) { - switch (i) { - case NodeActions.Attack: - i = 0; - break; - case NodeActions.Scan: - i = 1; - break; - case NodeActions.Weaken: - i = 2; - break; - case NodeActions.Fortify: - i = 3; - break; - case NodeActions.Overflow: - default: - i = 4; - break; - } - } - if (active) { - this.actionButtons[i].classList.remove("a-link-button-inactive"); - this.actionButtons[i].classList.add("a-link-button"); - } else { - this.actionButtons[i].classList.remove("a-link-button"); - this.actionButtons[i].classList.add("a-link-button-inactive"); - } - -} - -HackingMission.prototype.calculateAttacks = function() { - var total = 0; - for (var i = 0; i < this.playerCores.length; ++i) { - total += this.playerCores[i].atk; - } - for (var i = 0; i < this.playerNodes.length; ++i) { - total += this.playerNodes[i].atk; - } - this.playerAtk = total; - document.getElementById("hacking-mission-player-stats").innerHTML = - "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + - "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); - total = 0; - for (var i = 0; i < this.enemyCores.length; ++i) { - total += this.enemyCores[i].atk; - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - total += this.enemyDatabases[i].atk; - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - total += this.enemyNodes[i].atk; - } - this.enemyAtk = total; - document.getElementById("hacking-mission-enemy-stats").innerHTML = - "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + - "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); -} - -HackingMission.prototype.calculateDefenses = function() { - var total = 0; - for (var i = 0; i < this.playerCores.length; ++i) { - total += this.playerCores[i].def; - } - for (var i = 0; i < this.playerNodes.length; ++i) { - total += this.playerNodes[i].def; - } - this.playerDef = total; - document.getElementById("hacking-mission-player-stats").innerHTML = - "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + - "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); - total = 0; - for (var i = 0; i < this.enemyCores.length; ++i) { - total += this.enemyCores[i].def; - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - total += this.enemyDatabases[i].def; - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - total += this.enemyNodes[i].def; - } - this.enemyDef = total; - document.getElementById("hacking-mission-enemy-stats").innerHTML = - "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + - "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); -} - -HackingMission.prototype.removeAvailablePosition = function(x, y) { - for (var i = 0; i < this.availablePositions.length; ++i) { - if (this.availablePositions[i][0] === x && - this.availablePositions[i][1] === y) { - this.availablePositions.splice(i, 1); - return; - } - } - console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y); -} - -HackingMission.prototype.setNodePosition = function(nodeObj, x, y) { - if (!(nodeObj instanceof Node)) { - console.log("WARNING: Non-Node object passed into setNodePOsition"); - return; - } - if (isNaN(x) || isNaN(y)) { - console.log("ERR: Invalid values passed as x and y for setNodePosition"); - console.log(x); - console.log(y); - return; - } - nodeObj.pos = [x, y]; - this.map[x][y] = nodeObj; -} - -HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) { - var i = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.availablePositions.length - 1); - if (this.availablePositions[i][1] < xlimit) { - //Recurse if not within limit - return this.setNodeRandomPosition(nodeObj, xlimit); - } - var pos = this.availablePositions.splice(i, 1); - pos = pos[0]; - this.setNodePosition(nodeObj, pos[0], pos[1]); -} - -HackingMission.prototype.createMap = function() { - //Use a grid - var map = document.createElement("div"); - map.classList.add("hack-mission-grid"); - map.setAttribute("id", "hacking-mission-map"); - document.getElementById("mission-container").appendChild(map); - - //Create random Nodes for every space in the map that - //hasn't been filled yet. The stats of each Node will be based on - //the player/enemy attack - var averageAttack = (this.playerAtk + this.enemyAtk) / 2; - for (var x = 0; x < 8; ++x) { - for (var y = 0; y < 8; ++y) { - if (!(this.map[x][y] instanceof Node)) { - var node, type = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 2); - var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.85 + (this.difficulty / 2), 15); - switch (type) { - case 0: //Spam - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(200, 225) - } - node = new Node(NodeTypes.Spam, stats); - break; - case 1: //Transfer - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(250, 275) - } - node = new Node(NodeTypes.Transfer, stats); - break; - case 2: //Shield - default: - var stats = { - atk: 0, - def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 70), - hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(300, 320) - } - node = new Node(NodeTypes.Shield, stats); - break; - } - this.setNodePosition(node, x, y); - this.removeAvailablePosition(x, y); - this.miscNodes.push(node); - } - } - } - - //Create DOM elements in order - for (var r = 0; r < 8; ++r) { - for (var c = 0; c < 8; ++c) { - this.createNodeDomElement(this.map[r][c]); - } - } - - //Configure all Player CPUS - for (var i = 0; i < this.playerCores.length; ++i) { - console.log("Configuring Player Node: " + this.playerCores[i].el.id); - this.configurePlayerNodeElement(this.playerCores[i].el); - } -} - -HackingMission.prototype.createNodeDomElement = function(nodeObj) { - var nodeDiv = document.createElement("a"), txtEl = document.createElement('p'); - nodeObj.el = nodeDiv; - - //Set the node element's id based on its coordinates - var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; - nodeDiv.setAttribute("id", id); - txtEl.setAttribute("id", id + "-txt"); - - //Set node classes for owner - nodeDiv.classList.add("hack-mission-node"); - if (nodeObj.plyrCtrl) { - nodeDiv.classList.add("hack-mission-player-node"); - } else if (nodeObj.enmyCtrl) { - nodeDiv.classList.add("hack-mission-enemy-node"); - } - - //Set node classes based on type - var txt; - switch (nodeObj.type) { - case NodeTypes.Core: - txt = "CPU Core
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-cpu-node"); - break; - case NodeTypes.Firewall: - txt = "Firewall
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-firewall-node"); - break; - case NodeTypes.Database: - txt = "Database
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-database-node"); - break; - case NodeTypes.Spam: - txt = "Spam
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-spam-node"); - break; - case NodeTypes.Transfer: - txt = "Transfer
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-transfer-node"); - break; - case NodeTypes.Shield: - default: - txt = "Shield
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - nodeDiv.classList.add("hack-mission-shield-node"); - break; - } - - txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + - "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); - txtEl.innerHTML = txt; - - nodeDiv.appendChild(txtEl); - document.getElementById("hacking-mission-map").appendChild(nodeDiv); -} - -HackingMission.prototype.updateNodeDomElement = function(nodeObj) { - if (nodeObj.el == null) { - console.log("ERR: Calling updateNodeDomElement on a Node without an element"); - return; - } - - var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; - var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt"); - - //Set node classes based on type - var txt; - switch (nodeObj.type) { - case NodeTypes.Core: - txt = "CPU Core
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Firewall: - txt = "Firewall
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Database: - txt = "Database
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Spam: - txt = "Spam
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Transfer: - txt = "Transfer
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - case NodeTypes.Shield: - default: - txt = "Shield
" + "HP: " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); - break; - } - - txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + - "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); - if (nodeObj.action) { - txt += "
" + nodeObj.action; - } - txtEl.innerHTML = txt; -} - -//Gets a Node DOM element's corresponding Node object using its -//element id. Function accepts either the DOM element object or the ID as -//an argument -HackingMission.prototype.getNodeFromElement = function(el) { - var id; - if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(el)) { - id = el; - } else { - id = el.id; - } - id = id.replace("hacking-mission-node-", ""); - var res = id.split('-'); - if (res.length != 2) { - console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates"); - return null; - } - var x = res[0], y = res[1]; - if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) { - console.log("ERROR: Unexpected values for x and y: " + x + ", " + y); - return null; - } - return this.map[x][y]; -} - -function selectNode(hackMissionInst, el) { - var nodeObj = hackMissionInst.getNodeFromElement(el); - if (nodeObj == null) {console.log("Error getting Node object");} - if (!nodeObj.plyrCtrl) {return;} - - clearAllSelectedNodes(hackMissionInst); - nodeObj.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(nodeObj); -} - -function multiselectNode(hackMissionInst, el) { - var nodeObj = hackMissionInst.getNodeFromElement(el); - if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");} - if (!nodeObj.plyrCtrl) {return;} - - clearAllSelectedNodes(hackMissionInst); - var type = nodeObj.type; - if (type === NodeTypes.Core) { - hackMissionInst.playerCores.forEach(function(node) { - node.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(node); - }); - } else { - hackMissionInst.playerNodes.forEach(function(node) { - if (node.type === type) { - node.select(hackMissionInst.actionButtons); - hackMissionInst.selectedNode.push(node); - } - }); - } -} - -function clearAllSelectedNodes(hackMissionInst) { - if (hackMissionInst.selectedNode.length > 0) { - hackMissionInst.selectedNode.forEach(function(node){ - node.deselect(hackMissionInst.actionButtons); - }); - hackMissionInst.selectedNode.length = 0; - } -} - -//Configures a DOM element representing a player-owned node to -//be selectable and actionable -//Note: Does NOT change its css class. This is handled by Node.setControlledBy... -HackingMission.prototype.configurePlayerNodeElement = function(el) { - var nodeObj = this.getNodeFromElement(el); - if (nodeObj == null) {console.log("Error getting Node object");} - - //Add event listener - var self = this; - function selectNodeWrapper() { - selectNode(self, el); - } - el.addEventListener("click", selectNodeWrapper); - - function multiselectNodeWrapper() { - multiselectNode(self, el); - } - el.addEventListener("dblclick", multiselectNodeWrapper); - - - if (el.firstChild) { - el.firstChild.addEventListener("click", selectNodeWrapper); - } -} - -//Configures a DOM element representing an enemy-node by removing -//any event listeners -HackingMission.prototype.configureEnemyNodeElement = function(el) { - //Deselect node if it was the selected node - var nodeObj = this.getNodeFromElement(el); - for (var i = 0; i < this.selectedNode.length; ++i) { - if (this.selectedNode[i] == nodeObj) { - nodeObj.deselect(this.actionButtons); - this.selectedNode.splice(i, 1); - break; - } - } -} - -//Returns bool indicating whether a node is reachable by player -//by checking if any of the adjacent nodes are owned by the player -HackingMission.prototype.nodeReachable = function(node) { - var x = node.pos[0], y = node.pos[1]; - if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;} - if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;} - if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;} - if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;} - return false; -} - -HackingMission.prototype.nodeReachableByEnemy = function(node) { - if (node == null) {return false;} - var x = node.pos[0], y = node.pos[1]; - if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;} - if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;} - if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;} - if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;} - return false; -} - -HackingMission.prototype.start = function() { - this.started = true; - this.initJsPlumb(); - var startBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hack-mission-start-btn"); - startBtn.classList.remove("a-link-button"); - startBtn.classList.add("a-link-button-inactive"); -} - -HackingMission.prototype.initJsPlumb = function() { - var instance = jsPlumb.getInstance({ - DragOptions:{cursor:"pointer", zIndex:2000}, - PaintStyle: { - gradient: { stops: [ - [ 0, "#FFFFFF" ], - [ 1, "#FFFFFF" ] - ] }, - stroke: "#FFFFFF", - strokeWidth: 8 - }, - }); - - this.jsplumbinstance = instance; - - //All player cores are sources - for (var i = 0; i < this.playerCores.length; ++i) { - instance.makeSource(this.playerCores[i].el, { - deleteEndpointsOnEmpty:true, - maxConnections:1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - - //Everything else is a target - for (var i = 0; i < this.enemyCores.length; ++i) { - instance.makeTarget(this.enemyCores[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - for (var i = 0; i < this.enemyDatabases.length; ++i) { - instance.makeTarget(this.enemyDatabases[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:["Flowchart"] - }); - } - for (var i = 0; i < this.enemyNodes.length; ++i) { - instance.makeTarget(this.enemyNodes[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - for (var i = 0; i < this.miscNodes.length; ++i) { - instance.makeTarget(this.miscNodes[i].el, { - maxConnections:-1, - anchor:"Continuous", - connector:"Flowchart" - }); - } - - //Clicking a connection drops it - instance.bind("click", function(conn, originalEvent) { - var endpoints = conn.endpoints; - endpoints[0].detachFrom(endpoints[1]); - }); - - //Connection events - instance.bind("connection", (info)=>{ - var targetNode = this.getNodeFromElement(info.target); - - //Do not detach for enemy nodes - var thisNode = this.getNodeFromElement(info.source); - if (thisNode.enmyCtrl) {return;} - - //If the node is not reachable, drop the connection - if (!this.nodeReachable(targetNode)) { - info.sourceEndpoint.detachFrom(info.targetEndpoint); - return; - } - - var sourceNode = this.getNodeFromElement(info.source); - sourceNode.conn = info.connection; - var targetNode = this.getNodeFromElement(info.target); - ++targetNode.targetedCount; - }); - - //Detach Connection events - instance.bind("connectionDetached", (info, originalEvent)=>{ - var sourceNode = this.getNodeFromElement(info.source); - sourceNode.conn = null; - var targetNode = this.getNodeFromElement(info.target); - targetNode.untarget(); - }); - -} - -//Drops all connections where the specified node is the source -HackingMission.prototype.dropAllConnectionsFromNode = function(node) { - var allConns = this.jsplumbinstance.getAllConnections(); - for (var i = allConns.length-1; i >= 0; --i) { - if (allConns[i].source == node.el) { - allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); - } - } -} - -//Drops all connections where the specified node is the target -HackingMission.prototype.dropAllConnectionsToNode = function(node) { - var allConns = this.jsplumbinstance.getAllConnections(); - for (var i = allConns.length-1; i >= 0; --i) { - if (allConns[i].target == node.el) { - allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); - } - } - node.beingTargeted = false; -} - -var storedCycles = 0; -HackingMission.prototype.process = function(numCycles=1) { - if (!this.started) {return;} - storedCycles += numCycles; - if (storedCycles < 2) {return;} //Only process every 3 cycles minimum - - var res = false; - //Process actions of all player nodes - this.playerCores.forEach((node)=>{ - res |= this.processNode(node, storedCycles); - }); - - this.playerNodes.forEach((node)=>{ - if (node.type === NodeTypes.Transfer || - node.type === NodeTypes.Shield || - node.type === NodeTypes.Firewall) { - res |= this.processNode(node, storedCycles); - } - }); - - //Process actions of all enemy nodes - this.enemyCores.forEach((node)=>{ - this.enemyAISelectAction(node); - res |= this.processNode(node, storedCycles); - }); - - this.enemyNodes.forEach((node)=>{ - if (node.type === NodeTypes.Transfer || - node.type === NodeTypes.Shield || - node.type === NodeTypes.Firewall) { - this.enemyAISelectAction(node); - res |= this.processNode(node, storedCycles); - } - }); - - //The hp of enemy databases increases slowly - this.enemyDatabases.forEach((node)=>{ - node.maxhp += (0.1 * storedCycles); - node.hp += (0.1 * storedCycles); - }); - - if (res) { - this.calculateAttacks(); - this.calculateDefenses(); - } - - //Win if all enemy databases are conquered - if (this.enemyDatabases.length === 0) { - this.finishMission(true); - return; - } - - //Lose if all your cores are gone - if (this.playerCores.length === 0) { - this.finishMission(false); - return; - } - - //Defense/hp of misc nodes increases slowly over time - this.miscNodes.forEach((node)=>{ - node.def += (0.1 * storedCycles); - node.maxhp += (0.05 * storedCycles); - node.hp += (0.1 * storedCycles); - if (node.hp > node.maxhp) {node.hp = node.maxhp;} - this.updateNodeDomElement(node); - }); - - //Update timer and check if player lost - this.time -= (storedCycles * _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed); - if (this.time <= 0) { - this.finishMission(false); - return; - } - this.updateTimer(); - - storedCycles = 0; -} - -//Returns a bool representing whether defenses need to be re-calculated -HackingMission.prototype.processNode = function(nodeObj, numCycles=1) { - if (nodeObj.action == null) { - return; - } - - var targetNode = null, def, atk; - if (nodeObj.conn) { - if (nodeObj.conn.target != null) { - targetNode = this.getNodeFromElement(nodeObj.conn.target); - } else { - targetNode = this.getNodeFromElement(nodeObj.conn.targetId); - } - - if (targetNode == null) { - //Player is in the middle of dragging the connection, - //so the target node is null. Do nothing here - } else if (targetNode.plyrCtrl) { - def = this.playerDef; - atk = this.enemyAtk; - } else if (targetNode.enmyCtrl) { - def = this.enemyDef; - atk = this.playerAtk; - } else { //Misc Node - def = targetNode.def; - nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk; - } - } - - //Calculations are per second, so divide everything by 5 - var calcStats = false, plyr = nodeObj.plyrCtrl; - var enmyHacking = this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking; - switch(nodeObj.action) { - case NodeActions.Attack: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.hp -= (dmg/5 * numCycles); - break; - case NodeActions.Scan: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var eff = this.calculateScanEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.def -= (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Weaken: - if (targetNode == null) {break;} - if (nodeObj.conn == null) {break;} - var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); - targetNode.atk -= (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Fortify: - var eff = this.calculateFortifyEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); - nodeObj.def += (eff/5 * numCycles); - calcStats = true; - break; - case NodeActions.Overflow: - var eff = this.calculateOverflowEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); - if (nodeObj.def < eff) {break;} - nodeObj.def -= (eff/5 * numCycles); - nodeObj.atk += (eff/5 * numCycles); - calcStats = true; - break; - default: - console.log("ERR: Invalid Node Action: " + nodeObj.action); - break; - } - - //Stats can't go below 0 - if (nodeObj.atk < 0) {nodeObj.atk = 0;} - if (nodeObj.def < 0) {nodeObj.def = 0;} - if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;} - if (targetNode && targetNode.def < 0) {targetNode.def = 0;} - - //Conquering a node - if (targetNode && targetNode.hp <= 0) { - var conqueredByPlayer = nodeObj.plyrCtrl; - targetNode.hp = targetNode.maxhp; - targetNode.action = null; - targetNode.conn = null; - if (this.selectedNode == targetNode) { - targetNode.deselect(this.actionButtons); - } - - //The conquered node has its stats reduced - targetNode.atk /= 2; - targetNode.def /= 3.5; - - //Flag for whether the target node was a misc node - var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl; - - //Remove all connections from Node - this.dropAllConnectionsToNode(targetNode); - this.dropAllConnectionsFromNode(targetNode); - - //Changes the css class and turn the node into a JsPlumb Source/Target - if (conqueredByPlayer) { - targetNode.setControlledByPlayer(); - this.jsplumbinstance.unmakeTarget(targetNode.el); - this.jsplumbinstance.makeSource(targetNode.el, { - deleteEndpointsOnEmpty:true, - maxConnections:1, - anchor:"Continuous", - connector:"Flowchart" - }); - } else { - targetNode.setControlledByEnemy(); - nodeObj.conn = null; //Clear connection - this.jsplumbinstance.unmakeSource(targetNode.el); - this.jsplumbinstance.makeTarget(targetNode.el, { - maxConnections:-1, - anchor:"Continuous", - connector:["Flowchart"] - }); - } - - calcStats = true; - - //Helper function to swap nodes between the respective enemyNodes/playerNodes arrays - function swapNodes(orig, dest, targetNode) { - for (var i = 0; i < orig.length; ++i) { - if (orig[i] == targetNode) { - var node = orig.splice(i, 1); - node = node[0]; - dest.push(node); - break; - } - } - } - - switch(targetNode.type) { - case NodeTypes.Core: - if (conqueredByPlayer) { - swapNodes(this.enemyCores, this.playerCores, targetNode); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(this.playerCores, this.enemyCores, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Firewall: - if (conqueredByPlayer) { - swapNodes(this.enemyNodes, this.playerNodes, targetNode); - } else { - swapNodes(this.playerNodes, this.enemyNodes, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Database: - if (conqueredByPlayer) { - swapNodes(this.enemyDatabases, this.playerNodes, targetNode); - } else { - swapNodes(this.playerNodes, this.enemyDatabases, targetNode); - } - break; - case NodeTypes.Spam: - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - //Conquering spam node increases time limit - this.time += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease; - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - } - - break; - case NodeTypes.Transfer: - //Conquering a Transfer node increases the attack of all cores by some percentages - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - this.playerCores.forEach(function(node) { - node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; - }); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - this.enemyCores.forEach(function(node) { - node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; - }); - this.configureEnemyNodeElement(targetNode.el); - } - break; - case NodeTypes.Shield: - if (conqueredByPlayer) { - swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); - this.configurePlayerNodeElement(targetNode.el); - } else { - swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); - this.configureEnemyNodeElement(targetNode.el); - } - break; - } - - //If a misc node was conquered, the defense for all misc nodes increases by some fixed amount - if (isMiscNode) { //&& conqueredByPlayer) { - this.miscNodes.forEach((node)=>{ - if (node.targetedCount === 0) { - node.def *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease; - } - }); - } - } - - //Update node DOMs - this.updateNodeDomElement(nodeObj); - if (targetNode) {this.updateNodeDomElement(targetNode);} - return calcStats; -} - -//Enemy "AI" for CPU Core and Transfer Nodes -HackingMission.prototype.enemyAISelectAction = function(nodeObj) { - if (nodeObj == null) {return;} - switch(nodeObj.type) { - case NodeTypes.Core: - //Select a single RANDOM target from miscNodes and player's Nodes - //If it is reachable, it will target it. If not, no target will - //be selected for now, and the next time process() gets called this will repeat - if (nodeObj.conn == null) { - if (this.miscNodes.length === 0) { - //Randomly pick a player node and attack it if its reachable - var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerNodes.length-1); - var node; - if (this.playerNodes.length === 0) { - node = null; + if (env.stopFlag) {return Promise.reject(workerScript);} + switch (exp.type) { + case "BlockStatement": + case "Program": + var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment + return evaluateProgPromise.then(function(w) { + return Promise.resolve(workerScript); + }).catch(function(e) { + if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { + return Promise.reject(e); + } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { + workerScript.errorMessage = e; + return Promise.reject(workerScript); + } else if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { + return Promise.reject(e); } else { - node = this.playerNodes[rand]; + return Promise.reject(workerScript); } - if (this.nodeReachableByEnemy(node)) { - //Create connection - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el - }); - ++node.targetedCount; - } else { - //Randomly pick a player core and attack it if its reachable - rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerCores.length-1); - if (this.playerCores.length === 0) { - return; //No Misc Nodes, no player Nodes, no Player cores. Player lost - } else { - node = this.playerCores[rand]; - } + }); + break; + case "Literal": + return Promise.resolve(exp.value); + break; + case "Identifier": + //Javascript constructor() method can be used as an exploit to run arbitrary code + if (exp.name == "constructor") { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); + } - if (this.nodeReachableByEnemy(node)) { - //Create connection - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el + if (!(exp.name in env.vars)){ + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined", exp)); + } + return Promise.resolve(env.get(exp.name)) + break; + case "ExpressionStatement": + return evaluate(exp.expression, workerScript); + break; + case "ArrayExpression": + var argPromises = exp.elements.map(function(arg) { + return evaluate(arg, workerScript); + }); + return Promise.all(argPromises).then(function(array) { + return Promise.resolve(array) + }); + break; + case "CallExpression": + return evaluate(exp.callee, workerScript).then(function(func) { + return Promise.map(exp.arguments, function(arg) { + return evaluate(arg, workerScript); + }).then(function(args) { + if (func instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { //Player-defined function + //Create new Environment for the function + //Should be automatically garbage collected... + var funcEnv = env.extend(); + + //Define function arguments in this new environment + for (var i = 0; i < func.params.length; ++i) { + var arg; + if (i >= args.length) { + arg = null; + } else { + arg = args[i]; + } + funcEnv.def(func.params[i].name, arg); + } + + //Create a new WorkerScript for this function evaluation + var funcWorkerScript = new _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"](workerScript.scriptRef); + funcWorkerScript.serverIp = workerScript.serverIp; + funcWorkerScript.env = funcEnv; + workerScript.fnWorker = funcWorkerScript; + + return evaluate(func.body, funcWorkerScript).then(function(res) { + //If the function finished successfuly, that means there + //was no return statement since a return statement rejects. So resolve to null + workerScript.fnWorker = null; + return Promise.resolve(null); + }).catch(function(e) { + if (e.constructor === Array && e.length === 2 && e[0] === "RETURNSTATEMENT") { + //Return statement from function + return Promise.resolve(e[1]); + workerScript.fnWorker = null; + } else if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(e)) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); + } else if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { + //Parse out the err message from the WorkerScript and re-reject + var errorMsg = e.errorMessage; + var errorTextArray = errorMsg.split("|"); + if (errorTextArray.length === 4) { + errorMsg = errorTextArray[3]; + return Promise.reject(makeRuntimeRejectMsg(workerScript, errorMsg)); + } else { + if (env.stopFlag) { + return Promise.reject(workerScript); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error in one of your functions. Could not identify which function")); + } + } + } else if (e instanceof Error) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e.toString())); + } }); - ++node.targetedCount; + } else if (exp.callee.type === "MemberExpression"){ + return evaluate(exp.callee.object, workerScript).then(function(object) { + try { + if (func === "NETSCRIPTFOREACH") { + return evaluateForeach(object, args, workerScript).then(function(res) { + return Promise.resolve(res); + }).catch(function(e) { + return Promise.reject(e); + }); + } + var res = func.apply(object,args); + return Promise.resolve(res); + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); + } + }); + } else { + try { + var out = func.apply(null,args); + if (out instanceof Promise){ + return out.then(function(res) { + return Promise.resolve(res) + }).catch(function(e) { + if (isScriptErrorMessage(e)) { + //Functions don't have line number appended in error message, so add it + var num = getErrorLineNumber(exp, workerScript); + e += " (Line " + num + ")"; + } + return Promise.reject(e); + }); + } else { + return Promise.resolve(out); + } + } catch (e) { + if (isScriptErrorMessage(e)) { + if (isScriptErrorMessage(e)) { + //Functions don't have line number appended in error message, so add it + var num = getErrorLineNumber(exp, workerScript); + e += " (Line " + num + ")"; + } + return Promise.reject(e); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e, exp)); + } + } + } + }); + }); + break; + case "MemberExpression": + return evaluate(exp.object, workerScript).then(function(object) { + if (exp.computed){ + return evaluate(exp.property, workerScript).then(function(index) { + if (index >= object.length) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays", exp)); + } + return Promise.resolve(object[index]); + }).catch(function(e) { + if (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] || isScriptErrorMessage(e)) { + return Promise.reject(e); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression", exp)); + } + }); + } else { + if (exp.property.name === "constructor") { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Illegal usage of constructor() method. If you have your own function named 'constructor', you must re-name it.", exp)); + } + if (object != null && object instanceof Array && exp.property.name === "forEach") { + return "NETSCRIPTFOREACH"; + } + try { + return Promise.resolve(object[exp.property.name]) + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString(), exp)); + } + } + }); + break; + case "LogicalExpression": + case "BinaryExpression": + return evalBinary(exp, workerScript); + break; + case "UnaryExpression": + return evalUnary(exp, workerScript); + break; + case "AssignmentExpression": + return evalAssignment(exp, workerScript); + break; + case "UpdateExpression": + if (exp.argument.type==="Identifier"){ + if (exp.argument.name in env.vars){ + if (exp.operator === "++" || exp.operator === "--") { + switch (exp.operator) { + case "++": + env.set(exp.argument.name,env.get(exp.argument.name)+1); + break; + case "--": + env.set(exp.argument.name,env.get(exp.argument.name)-1); + break; + default: break; + } + return Promise.resolve(env.get(exp.argument.name)); + } + //Not sure what prefix UpdateExpressions there would be besides ++/-- + if (exp.prefix){ + return Promise.resolve(env.get(exp.argument.name)) + } + switch (exp.operator){ + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". You are trying to use code that is currently unsupported", exp)); + } + return Promise.resolve(env.get(exp.argument.name)) + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined", exp)); + } + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier", exp)); + } + break; + case "EmptyStatement": + return Promise.resolve(false); + break; + case "ReturnStatement": + return evaluate(exp.argument, workerScript).then(function(res) { + return Promise.reject(["RETURNSTATEMENT", res]); + }); + break; + case "BreakStatement": + return Promise.reject("BREAKSTATEMENT"); + break; + case "ContinueStatement": + return Promise.reject("CONTINUESTATEMENT"); + break; + case "IfStatement": + return evaluateIf(exp, workerScript); + break; + case "SwitchStatement": + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Switch statements are not yet implemented in Netscript", exp)); + break; + case "WhileStatement": + return evaluateWhile(exp, workerScript).then(function(res) { + return Promise.resolve(res); + }).catch(function(e) { + if (e == "BREAKSTATEMENT" || + (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { + return Promise.resolve("whileLoopBroken"); + } else { + return Promise.reject(e); + } + }); + break; + case "ForStatement": + return evaluate(exp.init, workerScript).then(function(expInit) { + return evaluateFor(exp, workerScript); + }).then(function(forLoopRes) { + return Promise.resolve("forLoopDone"); + }).catch(function(e) { + if (e == "BREAKSTATEMENT" || + (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "BREAKSTATEMENT")) { + return Promise.resolve("forLoopBroken"); + } else { + return Promise.reject(e); + } + }); + break; + case "FunctionDeclaration": + if (exp.id && exp.id.name) { + env.set(exp.id.name, exp); + return Promise.resolve(true); + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration", exp)); + } + break; + case "ImportDeclaration": + return evaluateImport(exp, workerScript).then(function(res) { + return Promise.resolve(res); + }).catch(function(e) { + return Promise.reject(e); + }); + break; + case "ThrowStatement": + return evaluate(exp.argument, workerScript).then(function(res) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, res)); + }); + break; + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is currently unsupported in Netscript", exp)); + break; + } //End switch + }).catch(function(e) { + return Promise.reject(e); + }); // End Promise +} + +function evalBinary(exp, workerScript){ + return evaluate(exp.left, workerScript).then(function(expLeft) { + //Short circuiting + if (expLeft == true && exp.operator === "||") { + return Promise.resolve(true); + } + if (expLeft == false && exp.operator === "&&") { + return Promise.resolve(false); + } + return evaluate(exp.right, workerScript).then(function(expRight) { + switch (exp.operator){ + case "===": + case "==": + return Promise.resolve(expLeft===expRight); + break; + case "!==": + case "!=": + return Promise.resolve(expLeft!==expRight); + break; + case "<": + return Promise.resolve(expLeft": + return Promise.resolve(expLeft>expRight); + break; + case ">=": + return Promise.resolve(expLeft>=expRight); + break; + case "+": + return Promise.resolve(expLeft+expRight); + break; + case "-": + return Promise.resolve(expLeft-expRight); + break; + case "*": + return Promise.resolve(expLeft*expRight); + break; + case "/": + if (expRight === 0) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero")); + } else { + return Promise.resolve(expLeft/expRight); + } + break; + case "%": + return Promise.resolve(expLeft%expRight); + break; + case "in": + return Promise.resolve(expLeft in expRight); + break; + case "instanceof": + return Promise.resolve(expLeft instanceof expRight); + break; + case "||": + return Promise.resolve(expLeft || expRight); + break; + case "&&": + return Promise.resolve(expLeft && expRight); + break; + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unsupported operator: " + exp.operator)); + } + }); + }); +} + +function evalUnary(exp, workerScript){ + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return evaluate(exp.argument, workerScript).then(function(res) { + if (exp.operator == "!") { + return Promise.resolve(!res); + } else if (exp.operator == "-") { + if (isNaN(res)) { + return Promise.resolve(res); + } else { + return Promise.resolve(-1 * res); + } + } else { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator)); + } + }); +} + +//Takes in a MemberExpression that should represent a Netscript array (possible multidimensional) +//The return value is an array of the form: +// [0th index (leftmost), array name, 1st index, 2nd index, ...] +function getArrayElement(exp, workerScript) { + var indices = []; + return evaluate(exp.property, workerScript).then(function(idx) { + if (isNaN(idx)) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx)); + } else { + if (exp.object.name === undefined && exp.object.object) { + return getArrayElement(exp.object, workerScript).then(function(res) { + res.push(idx); + indices = res; + return Promise.resolve(indices); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + indices.push(idx); + indices.push(exp.object.name); + return Promise.resolve(indices); + } + } + }); +} + +function evalAssignment(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + + if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left))); + } + + if (exp.operator !== "=" && !(exp.left.name in env.vars)){ + return Promise.reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined")); + } + + return evaluate(exp.right, workerScript).then(function(expRight) { + if (exp.left.type == "MemberExpression") { + if (!exp.left.computed) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to an object's property. This is currently unsupported in Netscript", exp)); + } + //Assign to array element + //Array object designed by exp.left.object.name + //Index designated by exp.left.property + return getArrayElement(exp.left, workerScript).then(function(res) { + if (!(res instanceof Array) || res.length < 2) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Error evaluating array assignment. This is (probably) a bug please report to game dev")); + } + + //The array name is the second value + var arrName = res.splice(1, 1); + arrName = arrName[0]; + + var res; + try { + res = env.setArrayElement(arrName, res, expRight); + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, e)); + } + return Promise.resolve(res); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + //Other assignments + try { + var assign; + switch (exp.operator) { + case "=": + assign = expRight; break; + case "+=": + assign = env.get(exp.left.name) + expRight; break; + case "-=": + assign = env.get(exp.left.name) - expRight; break; + case "*=": + assign = env.get(exp.left.name) * expRight; break; + case "/=": + assign = env.get(exp.left.name) / expRight; break; + case "%=": + assign = env.get(exp.left.name) % expRight; break; + default: + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented")); + } + env.set(exp.left.name, assign); + return Promise.resolve(assign); + } catch (e) { + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString())); + } + } + }); +} + +function evaluateIf(exp, workerScript, i) { + var env = workerScript.env; + return evaluate(exp.test, workerScript).then(function(condRes) { + if (condRes) { + return evaluate(exp.consequent, workerScript).then(function(res) { + return Promise.resolve(true); + }, function(e) { + return Promise.reject(e); + }); + } else if (exp.alternate) { + return evaluate(exp.alternate, workerScript).then(function(res) { + return Promise.resolve(true); + }, function(e) { + return Promise.reject(e); + }); + } else { + return Promise.resolve("endIf"); + } + }); +} + +//Evaluate the looping part of a for loop (Initialization block is NOT done in here) +function evaluateFor(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return new Promise(function(resolve, reject) { + function recurse() { + //Don't return a promise so the promise chain is broken on each recursion (saving memory) + evaluate(exp.test, workerScript).then(function(resCond) { + if (resCond) { + return evaluate(exp.body, workerScript).then(function(res) { + return evaluate(exp.update, workerScript); + }).catch(function(e) { + if (e == "CONTINUESTATEMENT" || + (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "CONTINUESTATEMENT")) { + //Continue statement, recurse to next iteration + return evaluate(exp.update, workerScript).then(function(resPostloop) { + return evaluateFor(exp, workerScript); + }).then(function(foo) { + return Promise.resolve("endForLoop"); + }).catch(function(e) { + return Promise.reject(e); + }); + } else { + return Promise.reject(e); + } + }).then(recurse, reject).catch(function(e) { + return Promise.reject(e); + }); + } else { + resolve(); + } + }).catch(function(e) { + reject(e); + }); + } + recurse(); + }); +} + +function evaluateForeach(arr, args, workerScript) { + console.log("evaluateForeach called"); + if (!(arr instanceof Array)) { + return Promise.reject("Invalid array passed into forEach"); + } + if (!(args instanceof Array) && args.length != 1) { + return Promise.reject("Invalid argument passed into forEach"); + } + var func = args[0]; + if (typeof func !== "function") { + return Promise.reject("Invalid function passed into forEach"); + } + console.log(func); + return new Promise(function(resolve, reject) { + //Don't return a promise so the promise chain is broken on each recursion + function recurse(i) { + console.log("recurse() called with i: " + i); + if (i >= arr.length) { + resolve(); + } else { + return Promise.delay(_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].CodeInstructionRunTime).then(function() { + console.log("About to apply function"); + var res = func.apply(null, [arr[i]]); + console.log("Applied function"); + ++i; + Promise.resolve(res).then(function(val) { + recurse(i); + }, reject).catch(function(e) { + return Promise.reject(e); + }); + }); + } + } + recurse(0); + }); +} + +function evaluateWhile(exp, workerScript) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + return new Promise(function (resolve, reject) { + function recurse() { + //Don't return a promise so the promise chain is broken on each recursion (saving memory) + evaluate(exp.test, workerScript).then(function(resCond) { + if (resCond) { + return evaluate(exp.body, workerScript).catch(function(e) { + if (e == "CONTINUESTATEMENT" || + (e instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"] && e.errorMessage == "CONTINUESTATEMENT")) { + //Continue statement, recurse + return evaluateWhile(exp, workerScript).then(function(foo) { + return Promise.resolve("endWhileLoop"); + }, function(e) { + return Promise.reject(e); + }); + } else { + return Promise.reject(e); + } + }).then(recurse, reject).catch(function(e) { + return Promise.reject(e); + }); + } else { + resolve(); + } + }).catch(function(e) { + reject(e); + }); + } + recurse(); + }); +} + +function evaluateProg(exp, workerScript, index) { + var env = workerScript.env; + if (env.stopFlag) {return Promise.reject(workerScript);} + if (index >= exp.body.length) { + return Promise.resolve("progFinished"); + } else { + //Evaluate this line of code in the prog + //After the code finishes evaluating, evaluate the next line recursively + return evaluate(exp.body[index], workerScript).then(function(res) { + return evaluateProg(exp, workerScript, index + 1); + }).then(function(res) { + return Promise.resolve(workerScript); + }).catch(function(e) { + return Promise.reject(e); + }); + } +} + +function evaluateImport(exp, workerScript, checkingRam=false) { + //When its checking RAM, it exports an array of nodes for each imported function + var ramCheckRes = []; + + var env = workerScript.env; + if (env.stopFlag) { + if (checkingRam) {return ramCheckRes;} + return Promise.reject(workerScript); + } + + //Get source script and name of all functions to import + var scriptName = exp.source.value; + var namespace, namespaceObj, allFns = false, fnNames = []; + if (exp.specifiers.length === 1 && exp.specifiers[0].type === "ImportNamespaceSpecifier") { + allFns = true; + namespace = exp.specifiers[0].local.name; + } else { + for (var i = 0; i < exp.specifiers.length; ++i) { + fnNames.push(exp.specifiers[i].local.name); + } + } + + //Get the code + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_5__["getServer"])(workerScript.serverIp), code = ""; + if (server == null) { + if (checkingRam) {return ramCheckRes;} + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to identify server. This is a bug please report to dev", exp)); + } + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename === scriptName) { + code = server.scripts[i].code; + break; + } + } + if (code === "") { + if (checkingRam) {return ramCheckRes;} + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Could not find script " + scriptName + " to import", exp)); + } + + //Create the AST + try { + var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["parse"])(code, {sourceType:"module"}); + } catch(e) { + console.log("Failed to parse import script"); + if (checkingRam) {return ramCheckRes;} + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Failed to import functions from " + scriptName + + " This is most likely due to a syntax error in the imported script", exp)); + } + + if (allFns) { + //A namespace is implemented as a JS obj + env.set(namespace, {}); + namespaceObj = env.get(namespace); + } + + //Search through the AST for all imported functions + var queue = [ast]; + while (queue.length != 0) { + var node = queue.shift(); + switch (node.type) { + case "BlockStatement": + case "Program": + for (var i = 0; i < node.body.length; ++i) { + if (node.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { + queue.push(node.body[i]); + } + } + break; + case "FunctionDeclaration": + if (node.id && node.id.name) { + if (allFns) { + //Import all functions under this namespace + if (checkingRam) { + ramCheckRes.push(node); + } else { + namespaceObj[node.id.name] = node; + } + } else { + //Only import specified functions + if (fnNames.includes(node.id.name)) { + if (checkingRam) { + ramCheckRes.push(node); + } else { + env.set(node.id.name, node); + } + } } } else { - //Randomly pick a misc node and attack it if its reachable - var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.miscNodes.length-1); - var node = this.miscNodes[rand]; - if (this.nodeReachableByEnemy(node)) { - nodeObj.conn = this.jsplumbinstance.connect({ - source:nodeObj.el, - target:node.el, - }); - ++node.targetedCount; - } + if (checkingRam) {return ramCheckRes;} + return Promise.reject(makeRuntimeRejectMsg(workerScript, "Invalid function declaration in imported script " + scriptName, exp)); } + break; + default: + break; + } - //If no connection was made, set the Core to Fortify - nodeObj.action = NodeActions.Fortify; + for (var prop in node) { + if (node.hasOwnProperty(prop)) { + if (node[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_8__["Node"]) { + queue.push(node[prop]); + } + } + } + } + if (!checkingRam) {workerScript.scriptRef.log("Imported functions from " + scriptName);} + if (checkingRam) {return ramCheckRes;} + return Promise.resolve(true); +} + +function killNetscriptDelay(workerScript) { + if (workerScript instanceof _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["WorkerScript"]) { + if (workerScript.delay) { + clearTimeout(workerScript.delay); + workerScript.delayResolve(); + } + } +} + +function netscriptDelay(time, workerScript) { + return new Promise(function(resolve, reject) { + workerScript.delay = setTimeout(()=>{ + workerScript.delay = null; + resolve(); + }, time); + workerScript.delayResolve = resolve; + }); +} + +function makeRuntimeRejectMsg(workerScript, msg, exp=null) { + var lineNum = ""; + if (exp != null) { + var num = getErrorLineNumber(exp, workerScript); + lineNum = " (Line " + num + ")" + } + return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg + lineNum; +} + +//Run a script from inside a script using run() command +function runScriptFromScript(server, scriptname, args, workerScript, threads=1) { + //Check if the script is already running + var runningScriptObj = Object(_Script_js__WEBPACK_IMPORTED_MODULE_7__["findRunningScript"])(scriptname, args, server); + if (runningScriptObj != null) { + workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname); + return Promise.resolve(false); + } + + //'null/undefined' arguments are not allowed + for (var i = 0; i < args.length; ++i) { + if (args[i] == null) { + workerScript.scriptRef.log("ERROR: Cannot execute a script with null/undefined as an argument"); + return Promise.resolve(false); + } + } + + //Check if the script exists and if it does run it + for (var i = 0; i < server.scripts.length; ++i) { + if (server.scripts[i].filename == scriptname) { + //Check for admin rights and that there is enough RAM availble to run + var script = server.scripts[i]; + var ramUsage = script.ramUsage; + threads = Math.round(Number(threads)); //Convert to number and round + ramUsage = ramUsage * threads * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, threads-1); + var ramAvailable = server.maxRam - server.ramUsed; + + if (server.hasAdminRights == false) { + workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!"); + return Promise.resolve(false); + } else if (ramUsage > ramAvailable){ + workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!"); + return Promise.resolve(false); } else { - //If this node has a selected target - var targetNode; - if (nodeObj.conn.target) { - targetNode = this.getNodeFromElement(nodeObj.conn.target); - } else { - targetNode = this.getNodeFromElement(nodeObj.conn.targetId); - } - if (targetNode == null) { - console.log("Error getting Target node Object in enemyAISelectAction()"); - } - - if (targetNode.def > this.enemyAtk + 15) { - if (nodeObj.def < 50) { - nodeObj.action = NodeActions.Fortify; - } else { - nodeObj.action = NodeActions.Overflow; - } - } else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) { - nodeObj.action = NodeActions.Scan; - } else { - nodeObj.action = NodeActions.Attack; - } + //Able to run script + workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_9__["printArray"])(args) + ". May take a few seconds to start up..."); + var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_7__["RunningScript"](script, args); + runningScriptObj.threads = threads; + server.runningScripts.push(runningScriptObj); //Push onto runningScripts + Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_4__["addWorkerScript"])(runningScriptObj, server); + return Promise.resolve(true); } - break; - case NodeTypes.Transfer: - //Switch between fortifying and overflowing as necessary - if (nodeObj.def < 125) { - nodeObj.action = NodeActions.Fortify; - } else { - nodeObj.action = NodeActions.Overflow; - } - break; - case NodeTypes.Firewall: - case NodeTypes.Shield: - nodeObj.action = NodeActions.Fortify; - break; - default: - break; - } -} - -var hackEffWeightSelf = 130; //Weight for Node actions on self -var hackEffWeightTarget = 25; //Weight for Node Actions against Target -var hackEffWeightAttack = 80; //Weight for Attack action - -//Returns damage per cycle based on stats -HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) { - return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1); -} - -HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) { - return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2); -} - -HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) { - return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2); -} - -HackingMission.prototype.calculateFortifyEffect = function(hacking=0) { - return 0.9 * hacking / hackEffWeightSelf; -} - -HackingMission.prototype.calculateOverflowEffect = function(hacking=0) { - return 0.95 * hacking / hackEffWeightSelf; -} - -//Updates timer display -HackingMission.prototype.updateTimer = function() { - var timer = document.getElementById("hacking-mission-timer"); - - //Convert time remaining to a string of the form mm:ss - var seconds = Math.round(this.time / 1000); - var minutes = Math.trunc(seconds / 60); - seconds %= 60; - var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2); - timer.innerText = "Time left: " + str; -} - -//The 'win' argument is a bool for whether or not the player won -HackingMission.prototype.finishMission = function(win) { - inMission = false; - currMission = null; - - if (win) { - var favorMult = 1 + (this.faction.favor / 100); - console.log("Hacking mission base reward: " + this.reward); - console.log("favorMult: " + favorMult); - console.log("rep mult: " + _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult); - var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " + - Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name); - _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain); - this.faction.playerReputation += gain; - } else { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation."); - } - - //Clear mission container - var container = document.getElementById("mission-container"); - while(container.firstChild) { - container.removeChild(container.firstChild); - } - - //Return to Faction page - document.getElementById("mainmenu-container").style.visibility = "visible"; - document.getElementById("character-overview-wrapper").style.visibility = "visible"; - _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); - Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name); -} - - - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) - -/***/ }), -/* 35 */ -/*!************************!*\ - !*** ./src/DarkWeb.js ***! - \************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkIfConnectedToDarkweb", function() { return checkIfConnectedToDarkweb; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeDarkwebTerminalCommand", function() { return executeDarkwebTerminalCommand; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listAllDarkwebItems", function() { return listAllDarkwebItems; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyDarkwebItem", function() { return buyDarkwebItem; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDarkwebItemPrice", function() { return parseDarkwebItemPrice; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DarkWebItems", function() { return DarkWebItems; }); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CreateProgram.js */ 14); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); - - - - - - - - - -/* DarkWeb.js */ -//Posts a "help" message if connected to DarkWeb -function checkIfConnectedToDarkweb() { - if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) { - var darkwebIp = _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"]["Darkweb Server"]; - if (!Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__["isValidIPAddress"])(darkwebIp)) {return;} - if (darkwebIp == _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getCurrentServer().ip) { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You are now connected to the dark web. From the dark web you can purchase illegal items. " + - "Use the 'buy -l' command to display a list of all the items you can buy. Use 'buy [item-name] " + - "to purchase an item"); } } - + workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname); + return Promise.resolve(false); } -//Handler for dark web commands. The terminal's executeCommand() function will pass -//dark web-specific commands into this. It will pass in the raw split command array -//rather than the command string -function executeDarkwebTerminalCommand(commandArray) { - if (commandArray.length == 0) {return;} - switch (commandArray[0]) { - case "buy": - if (commandArray.length != 2) { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Incorrect number of arguments. Usage: "); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy -l"); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy [item name]"); - return; - } - var arg = commandArray[1]; - if (arg == "-l") { - listAllDarkwebItems(); - } else { - buyDarkwebItem(arg); - } - break; - default: - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Command not found"); - break; - } -} +function getErrorLineNumber(exp, workerScript) { + var code = workerScript.scriptRef.scriptRef.code; -function listAllDarkwebItems() { - for (var item in DarkWebItems) { - if (DarkWebItems.hasOwnProperty(item)) { - var item = DarkWebItems[item]; - //Convert string using toLocaleString - var split = item.split(" - "); - if (split.length == 3 && split[1].charAt(0) == '$') { - split[1] = split[1].slice(1); - split[1] = split[1].replace(/,/g, ''); - var price = parseFloat(split[1]); - if (isNaN(price)) { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item); - return; - } - price = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(price, 0); - split[1] = "$" + price.toString(); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(split.join(" - ")); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item); - } - } - } - - var priceString = split[1]; - //Check for errors - if (priceString.length == 0 || priceString.charAt(0) != '$') { - return -1; - } - //Remove dollar sign and commas - priceString = priceString.slice(1); - priceString = priceString.replace(/,/g, ''); - - //Convert string to numeric - var price = parseFloat(priceString); - if (isNaN(price)) {return -1;} - else {return price;} -} - -function buyDarkwebItem(itemName) { - if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.BruteSSHProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the BruteSSH.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.FTPCrackProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the FTPCrack.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.RelaySMTPProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the relaySMTP.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.HTTPWormProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the HTTPWorm.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.SQLInjectProgram); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the SQLInject.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV1Program); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV1.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2.toLowerCase()) { - var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV2Program); - if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); - _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2); - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV2.exe program. The new program " + - "can be found on your home computer."); - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); - } - } else { - Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Unrecognized item"); - } -} - -function parseDarkwebItemPrice(itemDesc) { - var split = itemDesc.split(" - "); - if (split.length == 3) { - var priceString = split[1]; - //Check for errors - if (priceString.length == 0 || priceString.charAt(0) != '$') { - return -1; - } - //Remove dollar sign and commas - priceString = priceString.slice(1); - priceString = priceString.replace(/,/g, ''); - - //Convert string to numeric - var price = parseFloat(priceString); - if (isNaN(price)) {return -1;} - else {return price;} - } else { + //Split code up to the start of the node + try { + code = code.substring(0, exp.start); + return (code.match(/\n/g) || []).length + 1; + } catch(e) { return -1; } } -let DarkWebItems = { - BruteSSHProgram: "BruteSSH.exe - $500,000 - Opens up SSH Ports", - FTPCrackProgram: "FTPCrack.exe - $1,500,000 - Opens up FTP Ports", - RelaySMTPProgram: "relaySMTP.exe - $5,000,000 - Opens up SMTP Ports", - HTTPWormProgram: "HTTPWorm.exe - $30,000,000 - Opens up HTTP Ports", - SQLInjectProgram: "SQLInject.exe - $250,000,000 - Opens up SQL Ports", - DeepScanV1Program: "DeepscanV1.exe - $500,000 - Enables 'scan-analyze' with a depth up to 5", - DeepScanV2Program: "DeepscanV2.exe - $25,000,000 - Enables 'scan-analyze' with a depth up to 10", +function isScriptErrorMessage(msg) { + if (!Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["isString"])(msg)) {return false;} + let splitMsg = msg.split("|"); + if (splitMsg.length != 4){ + return false; + } + var ip = splitMsg[1]; + if (!Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_10__["isValidIPAddress"])(ip)) { + return false; + } + return true; +} + +//The same as Player's calculateHackingChance() function but takes in the server as an argument +function scriptCalculateHackingChance(server) { + var difficultyMult = (100 - server.hackDifficulty) / 100; + var skillMult = (1.75 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill) + (0.2 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence); + var skillChance = (skillMult - server.requiredHackingSkill) / skillMult; + var chance = skillChance * difficultyMult * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_chance_mult; + if (chance > 1) {return 1;} + if (chance < 0) {return 0;} + else {return chance;} +} + +//The same as Player's calculateHackingTime() function but takes in the server as an argument +function scriptCalculateHackingTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); + var hackingTime = 5 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds + return hackingTime; +} + +//The same as Player's calculateExpGain() function but takes in the server as an argument +function scriptCalculateExpGain(server) { + if (server.baseDifficulty == null) { + server.baseDifficulty = server.hackDifficulty; + } + return (server.baseDifficulty * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_exp_mult * 0.3 + 3) * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HackExpGain; +} + +//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument +function scriptCalculatePercentMoneyHacked(server) { + var difficultyMult = (100 - server.hackDifficulty) / 100; + var skillMult = (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill - (server.requiredHackingSkill - 1)) / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill; + var percentMoneyHacked = difficultyMult * skillMult * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_money_mult / 240; + if (percentMoneyHacked < 0) {return 0;} + if (percentMoneyHacked > 1) {return 1;} + return percentMoneyHacked * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].ScriptHackMoney; +} + +//Amount of time to execute grow() in milliseconds +function scriptCalculateGrowTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); + var growTime = 16 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds + return growTime * 1000; +} + +//Amount of time to execute weaken() in milliseconds +function scriptCalculateWeakenTime(server) { + var difficultyMult = server.requiredHackingSkill * server.hackDifficulty; + var skillFactor = (2.5 * difficultyMult + 500) / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_skill + 50 + (0.1 * _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].intelligence)); + var weakenTime = 20 * skillFactor / _Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].hacking_speed_mult; //This is in seconds + return weakenTime * 1000; } /***/ }), -/* 36 */ +/* 32 */ /*!************************!*\ !*** ./utils/acorn.js ***! \************************/ @@ -40139,7 +33764,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); }))); /***/ }), -/* 37 */ +/* 33 */ /*!*********************!*\ !*** ./src/Gang.js ***! \*********************/ @@ -40156,15 +33781,15 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteGangDisplayContent", function() { return deleteGangDisplayContent; }); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 9); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); /* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -41625,10 +35250,10 @@ function deleteGangDisplayContent() { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 38 */ +/* 34 */ /*!********************************************************!*\ !*** ./node_modules/jszip/lib/stream/GenericWorker.js ***! \********************************************************/ @@ -41901,7 +35526,7 @@ module.exports = GenericWorker; /***/ }), -/* 39 */ +/* 35 */ /*!********************************************!*\ !*** ./node_modules/jquery/dist/jquery.js ***! \********************************************/ @@ -52275,897 +45900,7 @@ return jQuery; /***/ }), -/* 40 */ -/*!****************************!*\ - !*** ./src/HacknetNode.js ***! - \****************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hacknetNodesInit", function() { return hacknetNodesInit; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HacknetNode", function() { return HacknetNode; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseHacknet", function() { return purchaseHacknet; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTotalHacknetProduction", function() { return updateTotalHacknetProduction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCostOfNextHacknetNode", function() { return getCostOfNextHacknetNode; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHacknetNodesMultiplierButtons", function() { return updateHacknetNodesMultiplierButtons; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMaxNumberLevelUpgrades", function() { return getMaxNumberLevelUpgrades; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayHacknetNodesContent", function() { return displayHacknetNodesContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHacknetNodesContent", function() { return updateHacknetNodesContent; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processAllHacknetNodeEarnings", function() { return processAllHacknetNodeEarnings; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHacknetNode", function() { return getHacknetNode; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPlayerHacknetNodeWrappers", function() { return createPlayerHacknetNodeWrappers; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 25); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); - - - - - - - - - - -/* HacknetNode.js */ -function hacknetNodesInit() { - var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); - mult1x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 1; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); - mult5x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 5; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); - mult10x.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 10; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); - var multMax = document.getElementById("hacknet-nodes-max-multiplier"); - multMax.addEventListener("click", function() { - hacknetNodePurchaseMultiplier = 0; - updateHacknetNodesMultiplierButtons(); - updateHacknetNodesContent(); - return false; - }); -} -document.addEventListener("DOMContentLoaded", hacknetNodesInit, false); - -function HacknetNode(name) { - this.level = 1; - this.ram = 1; //GB - this.cores = 1; - - this.name = name; - - this.totalMoneyGenerated = 0; - this.onlineTimeSeconds = 0; - - this.moneyGainRatePerSecond = 0; -} - - -HacknetNode.prototype.updateMoneyGainRate = function() { - //How much extra $/s is gained per level - var gainPerLevel = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMoneyGainPerLevel; - - this.moneyGainRatePerSecond = (this.level * gainPerLevel) * - Math.pow(1.035, this.ram-1) * - ((this.cores + 5) / 6) * - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult * - _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney; - if (isNaN(this.moneyGainRatePerSecond)) { - this.moneyGainRatePerSecond = 0; - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("Error in calculating Hacknet Node production. Please report to game developer"); - } - - updateTotalHacknetProduction(); -} - -HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) { - levels = Math.round(levels); - if (isNaN(levels) || levels < 1) {return 0;} - var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeLevelMult; - var totalMultiplier = 0; //Summed - var currLevel = this.level; - for (var i = 0; i < levels; ++i) { - totalMultiplier += Math.pow(mult, currLevel); - ++currLevel; - } - return _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode / 2 * totalMultiplier * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_level_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) { - return this.calculateLevelUpgradeCost(levels); -} - -HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { - levels = Math.round(levels); - var cost = this.calculateLevelUpgradeCost(levels); - if (isNaN(cost) || levels < 0) {return false;} - if (this.level + levels > _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) { - var diff = Math.max(0, _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - this.level); - return this.purchaseLevelUpgrade(diff); - } - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); - this.level += levels; - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeLevel = function(levels=1) { - return this.purchaseLevelUpgrade(levels); -} - -HacknetNode.prototype.calculateRamUpgradeCost = function() { - var numUpgrades = Math.log2(this.ram); - - //Calculate cost - //Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded - var baseCost = this.ram * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostFor1GBOfRamHacknetNode; - var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeRamMult, numUpgrades); - return baseCost * mult * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_ram_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getRamUpgradeCost = function() { - return this.calculateRamUpgradeCost(); -} - -HacknetNode.prototype.purchaseRamUpgrade = function() { - var cost = this.calculateRamUpgradeCost(); - if (isNaN(cost)) {return false;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} - if (this.ram >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) {return false;} - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); - this.ram *= 2; //Ram is always doubled - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeRam = function() { - return this.purchaseRamUpgrade(); -} - -HacknetNode.prototype.calculateCoreUpgradeCost = function() { - var coreBaseCost = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNodeCore; - var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeCoreMult; - return coreBaseCost * Math.pow(mult, this.cores-1) * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_core_cost_mult; -} - -//Wrapper function for Netscript -HacknetNode.prototype.getCoreUpgradeCost = function() { - return this.calculateCoreUpgradeCost(); -} - -HacknetNode.prototype.purchaseCoreUpgrade = function() { - var cost = this.calculateCoreUpgradeCost(); - if (isNaN(cost)) {return false;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} - if (this.cores >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) {return false;} - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); - ++this.cores; - this.updateMoneyGainRate(); - return true; -} - -//Wrapper function for Netscript -HacknetNode.prototype.upgradeCore = function() { - return this.purchaseCoreUpgrade(); -} - -/* Saving and loading HackNets */ -HacknetNode.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Generic_toJSON"])("HacknetNode", this); -} - -HacknetNode.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Generic_fromJSON"])(HacknetNode, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Reviver"].constructors.HacknetNode = HacknetNode; - -var HacknetNodeWrapper = function(hacknetNodeObj) { - var _node = hacknetNodeObj; - return { - name : _node.name, - level : _node.level, - ram : _node.ram, - cores : _node.cores, - totalMoneyGenerated : _node.totalMoneyGenerated, - onlineTimeSeconds : _node.onlineTimeSeconds, - moneyGainRatePerSecond : _node.moneyGainRatePerSecond, - upgradeLevel : function(n) { - return _node.upgradeLevel(n); - }, - upgradeRam : function() { - return _node.upgradeRam(); - }, - upgradeCore : function() { - return _node.upgradeCore(); - }, - getLevelUpgradeCost : function(n) { - return _node.getLevelUpgradeCost(n); - }, - getRamUpgradeCost : function() { - return _node.getRamUpgradeCost(); - }, - getCoreUpgradeCost : function() { - return _node.getCoreUpgradeCost(); - } - } -} - -function purchaseHacknet() { - /* INTERACTIVE TUTORIAL */ - if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialIsRunning"]) { - if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["currITutorialStep"] == _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialSteps"].HacknetNodesIntroduction) { - Object(_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialNextStep"])(); - } else { - return; - } - } - - /* END INTERACTIVE TUTORIAL */ - - var cost = getCostOfNextHacknetNode(); - if (isNaN(cost)) {throw new Error("Cost is NaN"); return;} - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) { - //dialogBoxCreate("You cannot afford to purchase a Hacknet Node!"); - return false; - } - - //Auto generate a name for the node for now...TODO - var numOwned = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; - var name = "hacknet-node-" + numOwned; - var node = new HacknetNode(name); - node.updateMoneyGainRate(); - - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.push(node); - - displayHacknetNodesContent(); - updateTotalHacknetProduction(); - return numOwned; -} - -//Calculates the total production from all HacknetNodes -function updateTotalHacknetProduction() { - var total = 0; - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - total += _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].moneyGainRatePerSecond; - } - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].totalHacknetNodeProduction = total; -} - -function getCostOfNextHacknetNode() { - //Cost increases exponentially based on how many you own - var numOwned = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; - var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodePurchaseNextMult; - return _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode * Math.pow(mult, numOwned) * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_purchase_cost_mult; -} - -var hacknetNodePurchaseMultiplier = 1; -function updateHacknetNodesMultiplierButtons() { - var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); - var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); - var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); - var multMax = document.getElementById("hacknet-nodes-max-multiplier"); - mult1x.setAttribute("class", "a-link-button"); - mult5x.setAttribute("class", "a-link-button"); - mult10x.setAttribute("class", "a-link-button"); - multMax.setAttribute("class", "a-link-button"); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length == 0) { - mult1x.setAttribute("class", "a-link-button-inactive"); - mult5x.setAttribute("class", "a-link-button-inactive"); - mult10x.setAttribute("class", "a-link-button-inactive"); - multMax.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 1) { - mult1x.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 5) { - mult5x.setAttribute("class", "a-link-button-inactive"); - } else if (hacknetNodePurchaseMultiplier == 10) { - mult10x.setAttribute("class", "a-link-button-inactive"); - } else { - multMax.setAttribute("class", "a-link-button-inactive"); - } -} - -//Calculate the maximum number of times the Player can afford to upgrade -//a Hacknet Node's level" -function getMaxNumberLevelUpgrades(nodeObj) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {return 0;} - var min = 1; - var max = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel-1; - var levelsToMax = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level; - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) { - return levelsToMax; - } - - while (min <= max) { - var curr = (min + max) / 2 | 0; - if (curr != _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel && - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) && - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr+1))) { - return Math.min(levelsToMax, curr); - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) { - max = curr - 1; - } else if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) { - min = curr + 1; - } else { - return Math.min(levelsToMax, curr); - } - } -} - -//Creates Hacknet Node DOM elements when the page is opened -function displayHacknetNodesContent() { - //Update Hacknet Nodes button - var newPurchaseButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("hacknet-nodes-purchase-button"); - - newPurchaseButton.addEventListener("click", function() { - purchaseHacknet(); - return false; - }); - - //Handle Purchase multiplier buttons - updateHacknetNodesMultiplierButtons(); - - //Remove all old hacknet Node DOM elements - var hacknetNodesList = document.getElementById("hacknet-nodes-list"); - while (hacknetNodesList.firstChild) { - hacknetNodesList.removeChild(hacknetNodesList.firstChild); - } - - //Then re-create them - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - createHacknetNodeDomElement(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); - } - updateHacknetNodesContent(); -} - -//Update information on all Hacknet Node DOM elements -function updateHacknetNodesContent() { - //Set purchase button to inactive if not enough money, and update its price display - var cost = getCostOfNextHacknetNode(); - var purchaseButton = document.getElementById("hacknet-nodes-purchase-button"); - purchaseButton.innerHTML = "Purchase Hacknet Node - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(cost, 2); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) { - purchaseButton.setAttribute("class", "a-link-button-inactive"); - } else { - purchaseButton.setAttribute("class", "a-link-button"); - } - - //Update player's money - var moneyElem = document.getElementById("hacknet-nodes-money"); - moneyElem.innerHTML = "Money: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.toNumber(), 2) + "
" + - "Total production from all Hacknet Nodes: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].totalHacknetNodeProduction, 2) + " / second"; - - //Update information in each owned hacknet node - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - updateHacknetNodeDomElement(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); - } -} - -//Creates a single Hacknet Node DOM element -function createHacknetNodeDomElement(nodeObj) { - var nodeName = nodeObj.name; - - var listItem = document.createElement("li"); - listItem.setAttribute("class", "hacknet-node"); - - var span = document.createElement("span"); - span.style.display = "inline"; - - var buttonDiv = document.createElement("div"); - buttonDiv.setAttribute("class", "hacknet-node-button-div"); - - //Text - var txt = document.createElement("p"); - //txt.setAttribute("id", "hacknet-node-text-" + nodeName); - txt.id = "hacknet-node-text-" + nodeName; - - //Upgrade buttons - var upgradeLevelButton = document.createElement("a"); - var upgradeRamButton = document.createElement("a"); - var upgradeCoreButton = document.createElement("a"); - - //upgradeLevelButton.setAttribute("id", "hacknet-node-upgrade-level-" + nodeName); - upgradeLevelButton.id = "hacknet-node-upgrade-level-" + nodeName; - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - upgradeLevelButton.addEventListener("click", function() { - var numUpgrades = hacknetNodePurchaseMultiplier; - if (hacknetNodePurchaseMultiplier == 0) { - numUpgrades = getMaxNumberLevelUpgrades(nodeObj); - } - nodeObj.purchaseLevelUpgrade(numUpgrades); - updateHacknetNodesContent(); - return false; - }); - //upgradeRamButton.setAttribute("id", "hacknet-node-upgrade-ram-" + nodeName); - upgradeRamButton.id = "hacknet-node-upgrade-ram-" + nodeName; - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - upgradeRamButton.addEventListener("click", function() { - nodeObj.purchaseRamUpgrade(); - updateHacknetNodesContent(); - return false; - }); - //upgradeCoreButton.setAttribute("id", "hacknet-node-upgrade-core-" + nodeName); - upgradeCoreButton.id = "hacknet-node-upgrade-core-" + nodeName; - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - upgradeCoreButton.addEventListener("click", function() { - nodeObj.purchaseCoreUpgrade(); - updateHacknetNodesContent(); - return false; - }); - - //Put all the components together in the li element - span.appendChild(txt); - buttonDiv.appendChild(upgradeLevelButton); - buttonDiv.appendChild(upgradeRamButton); - buttonDiv.appendChild(upgradeCoreButton); - span.appendChild(buttonDiv); - listItem.appendChild(span); - - document.getElementById("hacknet-nodes-list").appendChild(listItem); - - //Set the text and stuff inside the DOM element - updateHacknetNodeDomElement(nodeObj); -} - -//Updates information on a single hacknet node DOM element -function updateHacknetNodeDomElement(nodeObj) { - var nodeName = nodeObj.name; - var txt = document.getElementById("hacknet-node-text-" + nodeName); - if (txt == null) {throw new Error("Cannot find text element");} - txt.innerHTML = "Node name: " + nodeName + "
" + - "Production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(nodeObj.totalMoneyGenerated, 2) + - " ($" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(nodeObj.moneyGainRatePerSecond, 2) + " / second)
" + - "Level: " + nodeObj.level + "
" + - "RAM: " + nodeObj.ram + "GB
" + - "Cores: " + nodeObj.cores; - - //Upgrade level - var upgradeLevelButton = document.getElementById("hacknet-node-upgrade-level-" + nodeName); - if (upgradeLevelButton == null) {throw new Error("Cannot find upgrade level button element");} - if (nodeObj.level >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) { - upgradeLevelButton.innerHTML = "MAX LEVEL"; - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - } else { - var multiplier = 0; - if (hacknetNodePurchaseMultiplier == 0) { - //Max - multiplier = getMaxNumberLevelUpgrades(nodeObj); - } else { - var levelsToMax = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level; - multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); - } - - var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier); - upgradeLevelButton.innerHTML = "Upgrade Hacknet Node Level x" + multiplier + - " - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeLevelCost, 2); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeLevelCost)) { - upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeLevelButton.setAttribute("class", "a-link-button"); - } - } - - //Upgrade RAM - var upgradeRamButton = document.getElementById("hacknet-node-upgrade-ram-" + nodeName); - if (upgradeRamButton == null) {throw new Error("Cannot find upgrade ram button element");} - if (nodeObj.ram >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) { - upgradeRamButton.innerHTML = "MAX RAM"; - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - } else { - var upgradeRamCost = nodeObj.calculateRamUpgradeCost(); - upgradeRamButton.innerHTML = "Upgrade Hacknet Node RAM - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeRamCost, 2); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeRamCost)) { - upgradeRamButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeRamButton.setAttribute("class", "a-link-button"); - } - } - - //Upgrade Cores - var upgradeCoreButton = document.getElementById("hacknet-node-upgrade-core-" + nodeName); - if (upgradeCoreButton == null) {throw new Error("Cannot find upgrade cores button element");} - if (nodeObj.cores >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) { - upgradeCoreButton.innerHTML = "MAX CORES"; - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - } else { - var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(); - upgradeCoreButton.innerHTML = "Purchase additional CPU Core - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeCoreCost, 2); - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeCoreCost)) { - upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); - } else { - upgradeCoreButton.setAttribute("class", "a-link-button"); - } - } -} - -function createPlayerHacknetNodeWrappers() { - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i] = new HacknetNodeWrapper(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); - } -} - -function updatePlayerHacknetNodeWrappers() { - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length !== _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length) { - return createPlayerHacknetNodeWrappers(); - } - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length; ++i) { - if (!(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i] instanceof HacknetNodeWrapper)) {return createPlayerHacknetNodeWrappers();} - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].level = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].level; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].ram = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].ram; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].cores = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].cores; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].totalMoneyGenerated = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].totalMoneyGenerated; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].onlineTimeSeconds = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].onlineTimeSeconds; - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].moneyGainRatePerSecond = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].moneyGainRatePerSecond; - } -} - -function processAllHacknetNodeEarnings(numCycles) { - var total = 0; - updatePlayerHacknetNodeWrappers(); - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - total += processSingleHacknetNodeEarnings(numCycles, _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); - } - return total; -} - -function processSingleHacknetNodeEarnings(numCycles, nodeObj) { - var cyclesPerSecond = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed; - var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond; - if (isNaN(earningPerCycle)) { - console.log("ERROR: Hacknet Node Calculated earnings is NaN"); - earningPerCycle = 0; - } - var totalEarnings = numCycles * earningPerCycle; - nodeObj.totalMoneyGenerated += totalEarnings; - nodeObj.onlineTimeSeconds += (numCycles * (_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed / 1000)); - _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainMoney(totalEarnings); - return totalEarnings; -} - -function getHacknetNode(name) { - for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { - if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].name == name) { - return _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]; - } - } - return null; -} - - - - -/***/ }), -/* 41 */ -/*!********************************!*\ - !*** ./src/ActiveScriptsUI.js ***! - \********************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addActiveScriptsItem", function() { return addActiveScriptsItem; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteActiveScriptsItem", function() { return deleteActiveScriptsItem; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateActiveScriptsItems", function() { return updateActiveScriptsItems; }); -/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); -/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/LogBox.js */ 51); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); - - - - - - - - - - -/* { - * serverName: { - * header: Server Header Element - * panel: Server Panel List (ul) element - * scripts: { - * script id: Ref to Script information - * } - * } - * ... - */ -let ActiveScriptsUI = {}; -let ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements - -function createActiveScriptsServerPanel(server) { - let hostname = server.hostname; - - var activeScriptsList = document.getElementById("active-scripts-list"); - - let res = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({hdrText:hostname}); - let li = res[0]; - var hdr = res[1]; - let panel = res[2]; - - if (ActiveScriptsUI[hostname] != null) { - console.log("WARNING: Tried to create already-existing Active Scripts Server panel. This is most likely fine. It probably means many scripts just got started up on a new server. Aborting"); - return; - } - - var panelScriptList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("ul"); - panel.appendChild(panelScriptList); - activeScriptsList.appendChild(li); - - ActiveScriptsUI[hostname] = { - header: hdr, - panel: panel, - panelList: panelScriptList, - scripts: {}, //Holds references to li elements for each active script - scriptHdrs: {}, //Holds references to header elements for each active script - scriptStats: {} //Holds references to the p elements containing text for each active script - }; - - return li; -} - -//Deletes the info for a particular server (Dropdown header + Panel with all info) -//in the Active Scripts page if it exists -function deleteActiveScriptsServerPanel(server) { - let hostname = server.hostname; - if (ActiveScriptsUI[hostname] == null) { - console.log("WARNING: Tried to delete non-existent Active Scripts Server panel. Aborting"); - return; - } - - //Make sure it's empty - if (Object.keys(ActiveScriptsUI[hostname].scripts).length > 0) { - console.log("WARNING: Tried to delete Active Scripts Server panel that still has scripts. Aborting"); - return; - } - - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(ActiveScriptsUI[hostname].panel); - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(ActiveScriptsUI[hostname].header); - delete ActiveScriptsUI[hostname]; -} - -function addActiveScriptsItem(workerscript) { - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); - if (server == null) { - console.log("ERROR: Invalid server IP for workerscript in addActiveScriptsItem()"); - return; - } - let hostname = server.hostname; - - ActiveScriptsTasks.push(function(workerscript, hostname) { - if (ActiveScriptsUI[hostname] == null) { - createActiveScriptsServerPanel(server); - } - - //Create the unique identifier (key) for this script - var itemNameArray = ["active", "scripts", hostname, workerscript.name]; - for (var i = 0; i < workerscript.args.length; ++i) { - itemNameArray.push(String(workerscript.args[i])); - } - var itemName = itemNameArray.join("-"); - - let res = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({hdrText:workerscript.name}); - let li = res[0]; - let hdr = res[1]; - let panel = res[2]; - - hdr.classList.remove("accordion-header"); - hdr.classList.add("active-scripts-script-header"); - panel.classList.remove("accordion-panel"); - panel.classList.add("active-scripts-script-panel"); - - //Handle the constant elements on the panel that don't change after creation - //Threads, args, kill/log button - panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - innerHTML: "Threads: " + workerscript.scriptRef.threads + "
" + - "Args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["printArray"])(workerscript.args) - })); - var panelText = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { - innerText:"Loading...", fontSize:"14px", - }); - panel.appendChild(panelText); - panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br")); - panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("span", { - innerText:"Log", class:"active-scripts-button", margin:"4px", padding:"4px", - clickListener:()=>{ - Object(_utils_LogBox_js__WEBPACK_IMPORTED_MODULE_6__["logBoxCreate"])(workerscript.scriptRef); - return false; - } - })); - panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("span", { - innerText:"Kill Script", class:"active-scripts-button", margin:"4px", padding:"4px", - clickListener:()=>{ - Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["killWorkerScript"])(workerscript.scriptRef, workerscript.scriptRef.scriptRef.server); - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Killing script, may take a few minutes to complete..."); - return false; - } - })); - - //Append element to list - ActiveScriptsUI[hostname]["panelList"].appendChild(li); - ActiveScriptsUI[hostname].scripts[itemName] = li; - ActiveScriptsUI[hostname].scriptHdrs[itemName] = hdr; - ActiveScriptsUI[hostname].scriptStats[itemName] = panelText; - }.bind(null, workerscript, hostname)); -} - -function deleteActiveScriptsItem(workerscript) { - ActiveScriptsTasks.push(function(workerscript) { - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); - if (server == null) { - throw new Error("ERROR: Invalid server IP for workerscript. This most likely occurred because " + - "you tried to delete a large number of scripts and also deleted servers at the " + - "same time. It's not a big deal, just save and refresh the game."); - return; - } - let hostname = server.hostname; - if (ActiveScriptsUI[hostname] == null) { - console.log("ERROR: Trying to delete Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname); - return; - } - - var itemNameArray = ["active", "scripts", server.hostname, workerscript.name]; - for (var i = 0; i < workerscript.args.length; ++i) { - itemNameArray.push(String(workerscript.args[i])); - } - var itemName = itemNameArray.join("-"); - - let li = ActiveScriptsUI[hostname].scripts[itemName]; - if (li == null) { - console.log("ERROR: Cannot find Active Script UI element for workerscript: "); - console.log(workerscript); - return; - } - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(li); - delete ActiveScriptsUI[hostname].scripts[itemName]; - delete ActiveScriptsUI[hostname].scriptHdrs[itemName]; - delete ActiveScriptsUI[hostname].scriptStats[itemName]; - if (Object.keys(ActiveScriptsUI[hostname].scripts).length === 0) { - deleteActiveScriptsServerPanel(server); - } - }.bind(null, workerscript)); -} - -//Update the ActiveScriptsItems array -function updateActiveScriptsItems(maxTasks=100) { - //Run tasks that need to be done sequentially (adding items, creating/deleting server panels) - //We'll limit this to 50 at a time in case someone decides to start a bunch of scripts all at once... - let numTasks = Math.min(maxTasks, ActiveScriptsTasks.length); - for (let i = 0; i < numTasks; ++i) { - let task = ActiveScriptsTasks.shift(); - try { - task(); - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["exceptionAlert"])(e); - console.log(task); - } - } - - if (_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Page.ActiveScripts) {return;} - var total = 0; - for (var i = 0; i < _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["workerScripts"].length; ++i) { - try { - total += updateActiveScriptsItemContent(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["workerScripts"][i]); - } catch(e) { - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["exceptionAlert"])(e); - } - } - document.getElementById("active-scripts-total-prod").innerHTML = - "Total online production of Active Scripts: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(total).format('$0.000a') + " / sec
" + - "Total online production since last Aug installation: " + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].scriptProdSinceLastAug).format('$0.000a') + " (" + - numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].playtimeSinceLastAug/1000)).format('$0.000a') + " / sec)"; - return total; -} - -//Updates the content of the given item in the Active Scripts list -function updateActiveScriptsItemContent(workerscript) { - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); - if (server == null) { - console.log("ERROR: Invalid server IP for workerscript."); - return; - } - let hostname = server.hostname; - if (ActiveScriptsUI[hostname] == null) { - return; //Hasn't been created yet. We'll skip it - } - - var itemNameArray = ["active", "scripts", server.hostname, workerscript.name]; - for (var i = 0; i < workerscript.args.length; ++i) { - itemNameArray.push(String(workerscript.args[i])); - } - var itemName = itemNameArray.join("-"); - - if (ActiveScriptsUI[hostname].scriptStats[itemName] == null) { - return; //Hasn't been fully added yet. We'll skip it - } - var item = ActiveScriptsUI[hostname].scriptStats[itemName]; - - //Update the text if necessary. This fn returns the online $/s production - return updateActiveScriptsText(workerscript, item, itemName); -} - -function updateActiveScriptsText(workerscript, item, itemName) { - var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); - if (server == null) { - console.log("ERROR: Invalid server IP for workerscript."); - return; - } - let hostname = server.hostname; - if (ActiveScriptsUI[hostname] == null || ActiveScriptsUI[hostname].scriptHdrs[itemName] == null) { - console.log("ERROR: Trying to update Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname); - return; - } - - var onlineMps = workerscript.scriptRef.onlineMoneyMade / workerscript.scriptRef.onlineRunningTime; - - //Only update if the item is visible - if (ActiveScriptsUI[hostname].header.classList.contains("active") === false) {return onlineMps;} - if (ActiveScriptsUI[hostname].scriptHdrs[itemName].classList.contains("active") === false) {return onlineMps;} - - Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeChildrenFromElement"])(item); - - //Online - var onlineTotalMoneyMade = "Total online production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.onlineMoneyMade, 2); - var onlineTotalExpEarned = (Array(26).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.onlineExpGained, 2) + " hacking exp").replace( / /g, " "); - - var onlineMpsText = "Online production rate: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(onlineMps, 2) + "/second"; - var onlineEps = workerscript.scriptRef.onlineExpGained / workerscript.scriptRef.onlineRunningTime; - var onlineEpsText = (Array(25).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(onlineEps, 4) + " hacking exp/second").replace( / /g, " "); - - //Offline - var offlineTotalMoneyMade = "Total offline production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.offlineMoneyMade, 2); - var offlineTotalExpEarned = (Array(27).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.offlineExpGained, 2) + " hacking exp").replace( / /g, " "); - - var offlineMps = workerscript.scriptRef.offlineMoneyMade / workerscript.scriptRef.offlineRunningTime; - var offlineMpsText = "Offline production rate: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(offlineMps, 2) + "/second"; - var offlineEps = workerscript.scriptRef.offlineExpGained / workerscript.scriptRef.offlineRunningTime; - var offlineEpsText = (Array(26).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(offlineEps, 4) + " hacking exp/second").replace( / /g, " "); - - item.innerHTML = onlineTotalMoneyMade + "
" + onlineTotalExpEarned + "
" + - onlineMpsText + "
" + onlineEpsText + "
" + offlineTotalMoneyMade + "
" + offlineTotalExpEarned + "
" + - offlineMpsText + "
" + offlineEpsText + "
"; - return onlineMps; -} - - - - -/***/ }), -/* 42 */ +/* 36 */ /*!**********************************!*\ !*** ./src/CompanyManagement.js ***! \**********************************/ @@ -53174,20 +45909,20 @@ function updateActiveScriptsText(workerscript, item, itemName) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Corporation", function() { return Corporation; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Literature.js */ 53); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Literature_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Literature.js */ 49); /* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Location.js */ 4); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! decimal.js */ 24); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! decimal.js */ 20); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); -/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/min/numeral.min */ 13); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); /* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -58103,113 +50838,7 @@ _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Corpo /***/ }), -/* 43 */ -/*!*************************!*\ - !*** ./src/TextFile.js ***! - \*************************/ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextFile", function() { return TextFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTextFile", function() { return getTextFile; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createTextFile", function() { return createTextFile; }); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); - - - - -function TextFile(fn="", txt="") { - this.fn = fn.endsWith(".txt") ? fn : fn + ".txt"; - this.fn = this.fn.replace(/\s+/g, ''); - this.text = String(txt); -} - -TextFile.prototype.append = function(txt) { - this.text += String(txt); -} - -TextFile.prototype.write = function(txt) { - this.text = String(txt); -} - -TextFile.prototype.read = function() { - return this.txt; -} - -TextFile.prototype.show = function() { - Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(this.fn + "

" + this.text, true); -} - -TextFile.prototype.download = function() { - var filename = this.fn; - var file = new Blob([this.text], {type: 'text/plain'}); - if (window.navigator.msSaveOrOpenBlob) {// IE10+ - window.navigator.msSaveOrOpenBlob(file, filename); - } else { // Others - var a = document.createElement("a"), - url = URL.createObjectURL(file); - a.href = url; - a.download = this.fn; - document.body.appendChild(a); - a.click(); - setTimeout(function() { - document.body.removeChild(a); - window.URL.revokeObjectURL(url); - }, 0); - } -} - -TextFile.prototype.toJSON = function() { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Generic_toJSON"])("TextFile", this); -} - -TextFile.fromJSON = function(value) { - return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Generic_fromJSON"])(TextFile, value.data); -} - -_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Reviver"].constructors.TextFile = TextFile; - -function getTextFile(fn, server) { - if (!fn.endsWith(".txt")) {fn += ".txt";} - for (var i = 0; i < server.textFiles.length; ++i) { - if (server.textFiles[i].fn === fn) { - return server.textFiles[i]; - } - } - return null; -} - -//Returns the TextFile object that was just created -function createTextFile(fn, txt, server) { - if (getTextFile(fn, server) !== null) { - console.log("ERROR: createTextFile failed because the specified " + - "server already has a text file with the same fn"); - return; - } - var file = new TextFile(fn, txt); - server.textFiles.push(file); - return file; -} - -function deleteTextFile(fn, server) { - if (!fn.endsWith(".txt")) {fn += ".txt";} - for (var i = 0; i < server.textFiles.length; ++i) { - if (server.textFiles[i].fn === fn) { - server.textFiles.splice(i, 1); - return true; - } - } - return false; -} - - - - -/***/ }), -/* 44 */ +/* 37 */ /*!***************************!*\ !*** ./src/SourceFile.js ***! \***************************/ @@ -58222,7 +50851,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applySourceFile", function() { return applySourceFile; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSourceFiles", function() { return initSourceFiles; }); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 12); @@ -58418,7 +51047,5788 @@ function applySourceFile(srcFile) { /***/ }), -/* 45 */ +/* 38 */ +/*!****************************!*\ + !*** ./src/HacknetNode.js ***! + \****************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hacknetNodesInit", function() { return hacknetNodesInit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HacknetNode", function() { return HacknetNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseHacknet", function() { return purchaseHacknet; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateTotalHacknetProduction", function() { return updateTotalHacknetProduction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCostOfNextHacknetNode", function() { return getCostOfNextHacknetNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHacknetNodesMultiplierButtons", function() { return updateHacknetNodesMultiplierButtons; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMaxNumberLevelUpgrades", function() { return getMaxNumberLevelUpgrades; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "displayHacknetNodesContent", function() { return displayHacknetNodesContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHacknetNodesContent", function() { return updateHacknetNodesContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "processAllHacknetNodeEarnings", function() { return processAllHacknetNodeEarnings; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHacknetNode", function() { return getHacknetNode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPlayerHacknetNodeWrappers", function() { return createPlayerHacknetNodeWrappers; }); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InteractiveTutorial.js */ 21); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); + + + + + + + + + + +/* HacknetNode.js */ +function hacknetNodesInit() { + var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); + mult1x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 1; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); + mult5x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 5; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); + mult10x.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 10; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); + var multMax = document.getElementById("hacknet-nodes-max-multiplier"); + multMax.addEventListener("click", function() { + hacknetNodePurchaseMultiplier = 0; + updateHacknetNodesMultiplierButtons(); + updateHacknetNodesContent(); + return false; + }); +} +document.addEventListener("DOMContentLoaded", hacknetNodesInit, false); + +function HacknetNode(name) { + this.level = 1; + this.ram = 1; //GB + this.cores = 1; + + this.name = name; + + this.totalMoneyGenerated = 0; + this.onlineTimeSeconds = 0; + + this.moneyGainRatePerSecond = 0; +} + + +HacknetNode.prototype.updateMoneyGainRate = function() { + //How much extra $/s is gained per level + var gainPerLevel = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMoneyGainPerLevel; + + this.moneyGainRatePerSecond = (this.level * gainPerLevel) * + Math.pow(1.035, this.ram-1) * + ((this.cores + 5) / 6) * + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_money_mult * + _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].HacknetNodeMoney; + if (isNaN(this.moneyGainRatePerSecond)) { + this.moneyGainRatePerSecond = 0; + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_5__["dialogBoxCreate"])("Error in calculating Hacknet Node production. Please report to game developer"); + } + + updateTotalHacknetProduction(); +} + +HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) { + levels = Math.round(levels); + if (isNaN(levels) || levels < 1) {return 0;} + var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeLevelMult; + var totalMultiplier = 0; //Summed + var currLevel = this.level; + for (var i = 0; i < levels; ++i) { + totalMultiplier += Math.pow(mult, currLevel); + ++currLevel; + } + return _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode / 2 * totalMultiplier * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_level_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) { + return this.calculateLevelUpgradeCost(levels); +} + +HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) { + levels = Math.round(levels); + var cost = this.calculateLevelUpgradeCost(levels); + if (isNaN(cost) || levels < 0) {return false;} + if (this.level + levels > _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) { + var diff = Math.max(0, _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - this.level); + return this.purchaseLevelUpgrade(diff); + } + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); + this.level += levels; + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeLevel = function(levels=1) { + let res = this.purchaseLevelUpgrade(levels); + createPlayerHacknetNodeWrappers(); + return res; +} + +HacknetNode.prototype.calculateRamUpgradeCost = function() { + var numUpgrades = Math.log2(this.ram); + + //Calculate cost + //Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded + var baseCost = this.ram * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostFor1GBOfRamHacknetNode; + var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeRamMult, numUpgrades); + return baseCost * mult * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_ram_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getRamUpgradeCost = function() { + return this.calculateRamUpgradeCost(); +} + +HacknetNode.prototype.purchaseRamUpgrade = function() { + var cost = this.calculateRamUpgradeCost(); + if (isNaN(cost)) {return false;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} + if (this.ram >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) {return false;} + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); + this.ram *= 2; //Ram is always doubled + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeRam = function() { + let res = this.purchaseRamUpgrade(); + createPlayerHacknetNodeWrappers(); + return res; +} + +HacknetNode.prototype.calculateCoreUpgradeCost = function() { + var coreBaseCost = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNodeCore; + var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeUpgradeCoreMult; + return coreBaseCost * Math.pow(mult, this.cores-1) * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_core_cost_mult; +} + +//Wrapper function for Netscript +HacknetNode.prototype.getCoreUpgradeCost = function() { + let res = this.calculateCoreUpgradeCost(); + createPlayerHacknetNodeWrappers(); + return res; +} + +HacknetNode.prototype.purchaseCoreUpgrade = function() { + var cost = this.calculateCoreUpgradeCost(); + if (isNaN(cost)) {return false;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) {return false;} + if (this.cores >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) {return false;} + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); + ++this.cores; + this.updateMoneyGainRate(); + return true; +} + +//Wrapper function for Netscript +HacknetNode.prototype.upgradeCore = function() { + return this.purchaseCoreUpgrade(); +} + +/* Saving and loading HackNets */ +HacknetNode.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Generic_toJSON"])("HacknetNode", this); +} + +HacknetNode.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Generic_fromJSON"])(HacknetNode, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_7__["Reviver"].constructors.HacknetNode = HacknetNode; + +var HacknetNodeWrapper = function(hacknetNodeObj) { + var _node = hacknetNodeObj; + return { + name : _node.name, + level : _node.level, + ram : _node.ram, + cores : _node.cores, + totalMoneyGenerated : _node.totalMoneyGenerated, + onlineTimeSeconds : _node.onlineTimeSeconds, + moneyGainRatePerSecond : _node.moneyGainRatePerSecond, + upgradeLevel : function(n) { + return _node.upgradeLevel(n); + }, + upgradeRam : function() { + return _node.upgradeRam(); + }, + upgradeCore : function() { + return _node.upgradeCore(); + }, + getLevelUpgradeCost : function(n) { + return _node.getLevelUpgradeCost(n); + }, + getRamUpgradeCost : function() { + return _node.getRamUpgradeCost(); + }, + getCoreUpgradeCost : function() { + return _node.getCoreUpgradeCost(); + } + } +} + +function purchaseHacknet() { + /* INTERACTIVE TUTORIAL */ + if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialIsRunning"]) { + if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["currITutorialStep"] == _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialSteps"].HacknetNodesIntroduction) { + Object(_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialNextStep"])(); + } else { + return; + } + } + + /* END INTERACTIVE TUTORIAL */ + + var cost = getCostOfNextHacknetNode(); + if (isNaN(cost)) {throw new Error("Cost is NaN"); return;} + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) { + //dialogBoxCreate("You cannot afford to purchase a Hacknet Node!"); + return false; + } + + //Auto generate a name for the node for now...TODO + var numOwned = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; + var name = "hacknet-node-" + numOwned; + var node = new HacknetNode(name); + node.updateMoneyGainRate(); + + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].loseMoney(cost); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.push(node); + + if (_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Page.HacknetNodes) { + displayHacknetNodesContent(); + } + createPlayerHacknetNodeWrappers(); + updateTotalHacknetProduction(); + return numOwned; +} + +//Calculates the total production from all HacknetNodes +function updateTotalHacknetProduction() { + var total = 0; + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + total += _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].moneyGainRatePerSecond; + } + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].totalHacknetNodeProduction = total; +} + +function getCostOfNextHacknetNode() { + //Cost increases exponentially based on how many you own + var numOwned = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; + var mult = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodePurchaseNextMult; + return _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].BaseCostForHacknetNode * Math.pow(mult, numOwned) * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknet_node_purchase_cost_mult; +} + +var hacknetNodePurchaseMultiplier = 1; +function updateHacknetNodesMultiplierButtons() { + var mult1x = document.getElementById("hacknet-nodes-1x-multiplier"); + var mult5x = document.getElementById("hacknet-nodes-5x-multiplier"); + var mult10x = document.getElementById("hacknet-nodes-10x-multiplier"); + var multMax = document.getElementById("hacknet-nodes-max-multiplier"); + mult1x.setAttribute("class", "a-link-button"); + mult5x.setAttribute("class", "a-link-button"); + mult10x.setAttribute("class", "a-link-button"); + multMax.setAttribute("class", "a-link-button"); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length == 0) { + mult1x.setAttribute("class", "a-link-button-inactive"); + mult5x.setAttribute("class", "a-link-button-inactive"); + mult10x.setAttribute("class", "a-link-button-inactive"); + multMax.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 1) { + mult1x.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 5) { + mult5x.setAttribute("class", "a-link-button-inactive"); + } else if (hacknetNodePurchaseMultiplier == 10) { + mult10x.setAttribute("class", "a-link-button-inactive"); + } else { + multMax.setAttribute("class", "a-link-button-inactive"); + } +} + +//Calculate the maximum number of times the Player can afford to upgrade +//a Hacknet Node's level" +function getMaxNumberLevelUpgrades(nodeObj) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {return 0;} + var min = 1; + var max = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel-1; + var levelsToMax = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level; + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) { + return levelsToMax; + } + + while (min <= max) { + var curr = (min + max) / 2 | 0; + if (curr != _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel && + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) && + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr+1))) { + return Math.min(levelsToMax, curr); + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) { + max = curr - 1; + } else if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) { + min = curr + 1; + } else { + return Math.min(levelsToMax, curr); + } + } +} + +//Creates Hacknet Node DOM elements when the page is opened +function displayHacknetNodesContent() { + //Update Hacknet Nodes button + var newPurchaseButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["clearEventListeners"])("hacknet-nodes-purchase-button"); + + newPurchaseButton.addEventListener("click", function() { + purchaseHacknet(); + return false; + }); + + //Handle Purchase multiplier buttons + updateHacknetNodesMultiplierButtons(); + + //Remove all old hacknet Node DOM elements + var hacknetNodesList = document.getElementById("hacknet-nodes-list"); + while (hacknetNodesList.firstChild) { + hacknetNodesList.removeChild(hacknetNodesList.firstChild); + } + + //Then re-create them + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + createHacknetNodeDomElement(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); + } + updateHacknetNodesContent(); +} + +//Update information on all Hacknet Node DOM elements +function updateHacknetNodesContent() { + //Set purchase button to inactive if not enough money, and update its price display + var cost = getCostOfNextHacknetNode(); + var purchaseButton = document.getElementById("hacknet-nodes-purchase-button"); + purchaseButton.innerHTML = "Purchase Hacknet Node - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(cost, 2); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(cost)) { + purchaseButton.setAttribute("class", "a-link-button-inactive"); + } else { + purchaseButton.setAttribute("class", "a-link-button"); + } + + //Update player's money + var moneyElem = document.getElementById("hacknet-nodes-money"); + moneyElem.innerHTML = "Money: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.toNumber(), 2) + "
" + + "Total production from all Hacknet Nodes: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].totalHacknetNodeProduction, 2) + " / second"; + + //Update information in each owned hacknet node + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + updateHacknetNodeDomElement(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); + } +} + +//Creates a single Hacknet Node DOM element +function createHacknetNodeDomElement(nodeObj) { + var nodeName = nodeObj.name; + + var listItem = document.createElement("li"); + listItem.setAttribute("class", "hacknet-node"); + + var span = document.createElement("span"); + span.style.display = "inline"; + + var buttonDiv = document.createElement("div"); + buttonDiv.setAttribute("class", "hacknet-node-button-div"); + + //Text + var txt = document.createElement("p"); + //txt.setAttribute("id", "hacknet-node-text-" + nodeName); + txt.id = "hacknet-node-text-" + nodeName; + + //Upgrade buttons + var upgradeLevelButton = document.createElement("a"); + var upgradeRamButton = document.createElement("a"); + var upgradeCoreButton = document.createElement("a"); + + //upgradeLevelButton.setAttribute("id", "hacknet-node-upgrade-level-" + nodeName); + upgradeLevelButton.id = "hacknet-node-upgrade-level-" + nodeName; + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + upgradeLevelButton.addEventListener("click", function() { + var numUpgrades = hacknetNodePurchaseMultiplier; + if (hacknetNodePurchaseMultiplier == 0) { + numUpgrades = getMaxNumberLevelUpgrades(nodeObj); + } + nodeObj.purchaseLevelUpgrade(numUpgrades); + updateHacknetNodesContent(); + return false; + }); + //upgradeRamButton.setAttribute("id", "hacknet-node-upgrade-ram-" + nodeName); + upgradeRamButton.id = "hacknet-node-upgrade-ram-" + nodeName; + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + upgradeRamButton.addEventListener("click", function() { + nodeObj.purchaseRamUpgrade(); + updateHacknetNodesContent(); + return false; + }); + //upgradeCoreButton.setAttribute("id", "hacknet-node-upgrade-core-" + nodeName); + upgradeCoreButton.id = "hacknet-node-upgrade-core-" + nodeName; + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + upgradeCoreButton.addEventListener("click", function() { + nodeObj.purchaseCoreUpgrade(); + updateHacknetNodesContent(); + return false; + }); + + //Put all the components together in the li element + span.appendChild(txt); + buttonDiv.appendChild(upgradeLevelButton); + buttonDiv.appendChild(upgradeRamButton); + buttonDiv.appendChild(upgradeCoreButton); + span.appendChild(buttonDiv); + listItem.appendChild(span); + + document.getElementById("hacknet-nodes-list").appendChild(listItem); + + //Set the text and stuff inside the DOM element + updateHacknetNodeDomElement(nodeObj); +} + +//Updates information on a single hacknet node DOM element +function updateHacknetNodeDomElement(nodeObj) { + var nodeName = nodeObj.name; + var txt = document.getElementById("hacknet-node-text-" + nodeName); + if (txt == null) {throw new Error("Cannot find text element");} + txt.innerHTML = "Node name: " + nodeName + "
" + + "Production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(nodeObj.totalMoneyGenerated, 2) + + " ($" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(nodeObj.moneyGainRatePerSecond, 2) + " / second)
" + + "Level: " + nodeObj.level + "
" + + "RAM: " + nodeObj.ram + "GB
" + + "Cores: " + nodeObj.cores; + + //Upgrade level + var upgradeLevelButton = document.getElementById("hacknet-node-upgrade-level-" + nodeName); + if (upgradeLevelButton == null) {throw new Error("Cannot find upgrade level button element");} + if (nodeObj.level >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel) { + upgradeLevelButton.innerHTML = "MAX LEVEL"; + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + } else { + var multiplier = 0; + if (hacknetNodePurchaseMultiplier == 0) { + //Max + multiplier = getMaxNumberLevelUpgrades(nodeObj); + } else { + var levelsToMax = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxLevel - nodeObj.level; + multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier); + } + + var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier); + upgradeLevelButton.innerHTML = "Upgrade Hacknet Node Level x" + multiplier + + " - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeLevelCost, 2); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeLevelCost)) { + upgradeLevelButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeLevelButton.setAttribute("class", "a-link-button"); + } + } + + //Upgrade RAM + var upgradeRamButton = document.getElementById("hacknet-node-upgrade-ram-" + nodeName); + if (upgradeRamButton == null) {throw new Error("Cannot find upgrade ram button element");} + if (nodeObj.ram >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxRam) { + upgradeRamButton.innerHTML = "MAX RAM"; + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + } else { + var upgradeRamCost = nodeObj.calculateRamUpgradeCost(); + upgradeRamButton.innerHTML = "Upgrade Hacknet Node RAM - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeRamCost, 2); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeRamCost)) { + upgradeRamButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeRamButton.setAttribute("class", "a-link-button"); + } + } + + //Upgrade Cores + var upgradeCoreButton = document.getElementById("hacknet-node-upgrade-core-" + nodeName); + if (upgradeCoreButton == null) {throw new Error("Cannot find upgrade cores button element");} + if (nodeObj.cores >= _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].HacknetNodeMaxCores) { + upgradeCoreButton.innerHTML = "MAX CORES"; + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + } else { + var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost(); + upgradeCoreButton.innerHTML = "Purchase additional CPU Core - $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(upgradeCoreCost, 2); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].money.lt(upgradeCoreCost)) { + upgradeCoreButton.setAttribute("class", "a-link-button-inactive"); + } else { + upgradeCoreButton.setAttribute("class", "a-link-button"); + } + } +} + +function createPlayerHacknetNodeWrappers() { + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i] = new HacknetNodeWrapper(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); + } +} + +function updatePlayerHacknetNodeWrappers() { + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length !== _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length) { + return createPlayerHacknetNodeWrappers(); + } + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers.length; ++i) { + if (!(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i] instanceof HacknetNodeWrapper)) {return createPlayerHacknetNodeWrappers();} + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].level = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].level; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].ram = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].ram; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].cores = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].cores; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].totalMoneyGenerated = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].totalMoneyGenerated; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].onlineTimeSeconds = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].onlineTimeSeconds; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodeWrappers[i].moneyGainRatePerSecond = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].moneyGainRatePerSecond; + } +} + +function processAllHacknetNodeEarnings(numCycles) { + var total = 0; + updatePlayerHacknetNodeWrappers(); + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + total += processSingleHacknetNodeEarnings(numCycles, _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]); + } + return total; +} + +function processSingleHacknetNodeEarnings(numCycles, nodeObj) { + var cyclesPerSecond = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed; + var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond; + if (isNaN(earningPerCycle)) { + console.log("ERROR: Hacknet Node Calculated earnings is NaN"); + earningPerCycle = 0; + } + var totalEarnings = numCycles * earningPerCycle; + nodeObj.totalMoneyGenerated += totalEarnings; + nodeObj.onlineTimeSeconds += (numCycles * (_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"]._idleSpeed / 1000)); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainMoney(totalEarnings); + return totalEarnings; +} + +function getHacknetNode(name) { + for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes.length; ++i) { + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i].name == name) { + return _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacknetNodes[i]; + } + } + return null; +} + + + + +/***/ }), +/* 39 */ +/*!*************************!*\ + !*** ./src/Missions.js ***! + \*************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HackingMission", function() { return HackingMission; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "inMission", function() { return inMission; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setInMission", function() { return setInMission; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "currMission", function() { return currMission; }); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); +/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! jsplumb */ 197); +/* harmony import */ var jsplumb__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(jsplumb__WEBPACK_IMPORTED_MODULE_7__); + + + + + + + + + +let inMission = false; //Flag to denote whether a mission is running +let currMission = null; +function setInMission(bool, mission) { + inMission = bool; + if (bool) { + currMission = mission; + } else { + currMission = null; + } +} + +//Keyboard shortcuts +$(document).keydown(function(e) { + if (inMission && currMission && currMission.selectedNode.length != 0) { + switch (e.keyCode) { + case 65: //a for Attack + currMission.actionButtons[0].click(); + break; + case 83: //s for Scan + currMission.actionButtons[1].click(); + break; + case 87: //w for Weaken + currMission.actionButtons[2].click(); + break; + case 70: //f for Fortify + currMission.actionButtons[3].click(); + break; + case 82: //r for Overflow + currMission.actionButtons[4].click(); + break; + case 68: //d for Detach connection + currMission.actionButtons[5].click(); + break; + default: + break; + } + } +}); + +let NodeTypes = { + Core: "CPU Core Node", //All actions available + Firewall: "Firewall Node", //No actions available + Database: "Database Node", //No actions available + Spam: "Spam Node", //No actions Available + Transfer: "Transfer Node", //Can Weaken, Scan, Fortify and Overflow + Shield: "Shield Node" //Can Fortify +} + +let NodeActions = { + Attack: "Attacking", //Damaged based on attack stat + hacking level + opp def + Scan: "Scanning", //-Def for target, affected by attack and hacking level + Weaken: "Weakening", //-Attack for target, affected by attack and hacking level + Fortify: "Fortifying", //+Defense for Node, affected by hacking level + Overflow: "Overflowing", //+Attack but -Defense for Node, affected by hacking level +} + +function Node(type, stats) { + this.type = type; + this.atk = stats.atk ? stats.atk : 0; + this.def = stats.def ? stats.def : 0; + this.hp = stats.hp ? stats.hp : 0; + this.maxhp = this.hp; + this.plyrCtrl = false; + this.enmyCtrl = false; + this.pos = [0, 0]; //x, y + this.el = null; //Holds the Node's DOM element + this.action = null; + this.targetedCount = 0; //Count of how many connections this node is the target of + + //Holds the JsPlumb Connection object for this Node, + //where this Node is the Source (since each Node + //can only have 1 outgoing Connection) + this.conn = null; +} + +Node.prototype.setPosition = function(x, y) { + this.pos = [x, y]; +} + +Node.prototype.setControlledByPlayer = function() { + this.plyrCtrl = true; + this.enmyCtrl = false; + if (this.el) { + this.el.classList.remove("hack-mission-enemy-node"); + this.el.classList.add("hack-mission-player-node"); + } +} + +Node.prototype.setControlledByEnemy = function() { + this.plyrCtrl = false; + this.enmyCtrl = true; + if (this.el) { + this.el.classList.remove("hack-mission-player-node"); + this.el.classList.add("hack-mission-enemy-node"); + } +} + +//Sets this node to be the active node +Node.prototype.select = function(actionButtons) { + if (this.enmyCtrl) {return;} + this.el.classList.add("hack-mission-player-node-active"); + + //Make all buttons inactive + for (var i = 0; i < actionButtons.length; ++i) { + actionButtons[i].classList.remove("a-link-button"); + actionButtons[i].classList.add("a-link-button-inactive"); + } + + switch(this.type) { + case NodeTypes.Core: + //All buttons active + for (var i = 0; i < actionButtons.length; ++i) { + actionButtons[i].classList.remove("a-link-button-inactive"); + actionButtons[i].classList.add("a-link-button"); + } + break; + case NodeTypes.Transfer: + actionButtons[1].classList.remove("a-link-button-inactive"); + actionButtons[1].classList.add("a-link-button"); + actionButtons[2].classList.remove("a-link-button-inactive"); + actionButtons[2].classList.add("a-link-button"); + actionButtons[3].classList.remove("a-link-button-inactive"); + actionButtons[3].classList.add("a-link-button"); + actionButtons[4].classList.remove("a-link-button-inactive"); + actionButtons[4].classList.add("a-link-button"); + actionButtons[5].classList.remove("a-link-button-inactive"); + actionButtons[5].classList.add("a-link-button"); + break; + case NodeTypes.Shield: + case NodeTypes.Firewall: + actionButtons[3].classList.remove("a-link-button-inactive"); + actionButtons[3].classList.add("a-link-button"); + break; + default: + break; + } +} + +Node.prototype.deselect = function(actionButtons) { + this.el.classList.remove("hack-mission-player-node-active"); + for (var i = 0; i < actionButtons.length; ++i) { + actionButtons[i].classList.remove("a-link-button"); + actionButtons[i].classList.add("a-link-button-inactive"); + } +} + + +Node.prototype.untarget = function() { + if (this.targetedCount === 0) { + console.log("WARN: Node " + this.el.id + " is being 'untargeted' when it has no target count"); + return; + } + --this.targetedCount; +} + +//Hacking mission instance +//Takes in the reputation of the Faction for which the mission is +//being conducted +function HackingMission(rep, fac) { + this.faction = fac; + + this.started = false; + this.time = 180000; //5 minutes to start, milliseconds + + this.playerCores = []; + this.playerNodes = []; //Non-core nodes + this.playerAtk = 0; + this.playerDef = 0; + + this.enemyCores = []; + this.enemyDatabases = []; + this.enemyNodes = []; //Non-core nodes + this.enemyAtk = 0; + this.enemyDef = 0; + + this.miscNodes = []; + + this.selectedNode = []; //Which of the player's nodes are currently selected + + this.actionButtons = []; //DOM buttons for actions + + this.availablePositions = []; + for (var r = 0; r < 8; ++r) { + for (var c = 0; c < 8; ++c) { + this.availablePositions.push([r, c]); + } + } + + this.map = []; + for (var i = 0; i < 8; ++i) { + this.map.push([null, null, null, null, null, null, null, null]); + } + + this.jsplumbinstance = null; + + this.difficulty = rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToDiffConversion + 1; + console.log("difficulty: " + this.difficulty); + this.reward = 250 + (rep / _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionRepToRewardConversion); +} + +HackingMission.prototype.init = function() { + //Create Header DOM + this.createPageDom(); + + //Create player starting nodes + var home = _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer() + for (var i = 0; i < home.cpuCores; ++i) { + var stats = { + atk: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 7.5) + 30, + def: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 20), + hp: (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill / 4), + }; + this.playerCores.push(new Node(NodeTypes.Core, stats)); + this.playerCores[i].setControlledByPlayer(); + this.setNodePosition(this.playerCores[i], i, 0); + this.removeAvailablePosition(i, 0); + } + + //Randomly generate enemy nodes (CPU and Firewall) based on difficulty + var numNodes = Math.min(8, Math.max(1, Math.round(this.difficulty / 4))); + var numFirewalls = Math.min(20, + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(Math.round(this.difficulty/3), Math.round(this.difficulty/3) + 1)); + var numDatabases = Math.min(10, Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(1, Math.round(this.difficulty / 3) + 1)); + var totalNodes = numNodes + numFirewalls + numDatabases; + var xlimit = 7 - Math.floor(totalNodes / 8); + var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.8 + (this.difficulty / 5), 10); + for (var i = 0; i < numNodes; ++i) { + var stats = { + atk: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(80, 86), + def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(5, 10), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 230) + } + this.enemyCores.push(new Node(NodeTypes.Core, stats)); + this.enemyCores[i].setControlledByEnemy(); + this.setNodeRandomPosition(this.enemyCores[i], xlimit); + } + for (var i = 0; i < numFirewalls; ++i) { + var stats = { + atk: 0, + def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(10, 20), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(275, 300) + } + this.enemyNodes.push(new Node(NodeTypes.Firewall, stats)); + this.enemyNodes[i].setControlledByEnemy(); + this.setNodeRandomPosition(this.enemyNodes[i], xlimit); + } + for (var i = 0; i < numDatabases; ++i) { + var stats = { + atk: 0, + def: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 55), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(210, 275) + } + var node = new Node(NodeTypes.Database, stats); + node.setControlledByEnemy(); + this.setNodeRandomPosition(node, xlimit); + this.enemyDatabases.push(node); + } + this.calculateDefenses(); + this.calculateAttacks(); + this.createMap(); +} + +HackingMission.prototype.createPageDom = function() { + var container = document.getElementById("mission-container"); + + var favorMult = 1 + (this.faction.favor / 100); + var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; + var headerText = document.createElement("p"); + headerText.innerHTML = "You are about to start a hacking mission! You will gain " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " faction reputation with " + this.faction.name + + " if you win. For more information " + + "about how hacking missions work, click one of the guide links " + + "below (one opens up an in-game guide and the other opens up " + + "the guide from the wiki). Click the 'Start' button to begin."; + headerText.style.display = "block"; + headerText.classList.add("hack-mission-header-element"); + headerText.style.width = "80%"; + + var inGameGuideBtn = document.createElement("a"); + inGameGuideBtn.innerText = "How to Play"; + inGameGuideBtn.classList.add("a-link-button"); + inGameGuideBtn.style.display = "inline-block"; + inGameGuideBtn.classList.add("hack-mission-header-element"); + inGameGuideBtn.addEventListener("click", function() { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionHowToPlay); + return false; + }); + + var wikiGuideBtn = document.createElement("a"); + wikiGuideBtn.innerText = "Wiki Guide"; + wikiGuideBtn.classList.add("a-link-button"); + wikiGuideBtn.style.display = "inline-block"; + wikiGuideBtn.classList.add("hack-mission-header-element"); + wikiGuideBtn.target = "_blank"; + //TODO Add link to wiki page wikiGuideBtn.href = + + + //Start button will get replaced with forfeit when game is started + var startBtn = document.createElement("a"); + startBtn.innerHTML = "Start"; + startBtn.setAttribute("id", "hack-mission-start-btn"); + startBtn.classList.add("a-link-button"); + startBtn.classList.add("hack-mission-header-element"); + startBtn.style.display = "inline-block"; + startBtn.addEventListener("click", ()=>{ + this.start(); + return false; + }); + + var forfeitMission = document.createElement("a"); + forfeitMission.innerHTML = "Forfeit Mission (Exit)"; + forfeitMission.classList.add("a-link-button"); + forfeitMission.classList.add("hack-mission-header-element"); + forfeitMission.style.display = "inline-block"; + forfeitMission.addEventListener("click", ()=> { + this.finishMission(false); + return false; + }); + + var timer = document.createElement("p"); + timer.setAttribute("id", "hacking-mission-timer"); + timer.style.display = "inline-block"; + timer.style.margin = "6px"; + + //Create Action Buttons (Attack/Scan/Weaken/ etc...) + var actionsContainer = document.createElement("span"); + actionsContainer.style.display = "block"; + actionsContainer.classList.add("hack-mission-action-buttons-container"); + for (var i = 0; i < 6; ++i) { + this.actionButtons.push(document.createElement("a")); + this.actionButtons[i].style.display = "inline-block"; + this.actionButtons[i].classList.add("a-link-button-inactive"); //Disabled at start + this.actionButtons[i].classList.add("tooltip"); //Disabled at start + this.actionButtons[i].classList.add("hack-mission-header-element"); + actionsContainer.appendChild(this.actionButtons[i]); + } + this.actionButtons[0].innerText = "Attack(a)"; + var atkTooltip = document.createElement("span"); + atkTooltip.classList.add("tooltiptexthigh"); + atkTooltip.innerText = "Lowers the targeted node's HP. The effectiveness of this depends on " + + "this node's Attack level, your hacking level, and the opponent's defense level."; + this.actionButtons[0].appendChild(atkTooltip); + this.actionButtons[1].innerText = "Scan(s)"; + var scanTooltip = document.createElement("span"); + scanTooltip.classList.add("tooltiptexthigh"); + scanTooltip.innerText = "Lowers the targeted node's defense. The effectiveness of this depends on " + + "this node's Attack level, your hacking level, and the opponent's defense level."; + this.actionButtons[1].appendChild(scanTooltip); + this.actionButtons[2].innerText = "Weaken(w)"; + var WeakenTooltip = document.createElement("span"); + WeakenTooltip.classList.add("tooltiptexthigh"); + WeakenTooltip.innerText = "Lowers the targeted node's attack. The effectiveness of this depends on " + + "this node's Attack level, your hacking level, and the opponent's defense level."; + this.actionButtons[2].appendChild(WeakenTooltip); + this.actionButtons[3].innerText = "Fortify(f)"; + var fortifyTooltip = document.createElement("span"); + fortifyTooltip.classList.add("tooltiptexthigh"); + fortifyTooltip.innerText = "Raises this node's Defense level. The effectiveness of this depends on " + + "your hacking level"; + this.actionButtons[3].appendChild(fortifyTooltip); + this.actionButtons[4].innerText = "Overflow(r)"; + var overflowTooltip = document.createElement("span"); + overflowTooltip.classList.add("tooltiptexthigh"); + overflowTooltip.innerText = "Raises this node's Attack level but lowers its Defense level. The effectiveness " + + "of this depends on your hacking level."; + this.actionButtons[4].appendChild(overflowTooltip); + this.actionButtons[5].innerText = "Drop Connection(d)"; + var dropconnTooltip = document.createElement("span"); + dropconnTooltip.classList.add("tooltiptexthigh"); + dropconnTooltip.innerText = "Removes this Node's current connection to some target Node, if it has one. This can " + + "also be done by simply clicking the white connection line."; + this.actionButtons[5].appendChild(dropconnTooltip); + + //Player/enemy defense displays will be in action container + var playerStats = document.createElement("p"); + var enemyStats = document.createElement("p"); + playerStats.style.display = "inline-block"; + enemyStats.style.display = "inline-block"; + playerStats.style.color = "#00ccff"; + enemyStats.style.color = "red"; + playerStats.style.margin = "4px"; + enemyStats.style.margin = "4px"; + playerStats.setAttribute("id", "hacking-mission-player-stats"); + enemyStats.setAttribute("id", "hacking-mission-enemy-stats"); + actionsContainer.appendChild(playerStats); + actionsContainer.appendChild(enemyStats); + + //Set Action Button event listeners + this.actionButtons[0].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + if (this.selectedNode[0].type !== NodeTypes.Core) {return;} + this.setActionButtonsActive(this.selectedNode[0].type); + this.setActionButton(NodeActions.Attack, false); //Set attack button inactive + this.selectedNode.forEach(function(node){ + node.action = NodeActions.Attack; + }); + }); + + this.actionButtons[1].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type + if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} + this.setActionButtonsActive(nodeType); + this.setActionButton(NodeActions.Scan, false); //Set scan button inactive + this.selectedNode.forEach(function(node){ + node.action = NodeActions.Scan; + }); + }); + + this.actionButtons[2].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + var nodeType = this.selectedNode[0].type; //In a multiselect, every Node will have the same type + if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} + this.setActionButtonsActive(nodeType); + this.setActionButton(NodeActions.Weaken, false); //Set Weaken button inactive + this.selectedNode.forEach(function(node){ + node.action = NodeActions.Weaken; + }); + }); + + this.actionButtons[3].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + this.setActionButtonsActive(this.selectedNode[0].type); + this.setActionButton(NodeActions.Fortify, false); //Set Fortify button inactive + this.selectedNode.forEach(function(node){ + node.action = NodeActions.Fortify; + }); + }); + + this.actionButtons[4].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + var nodeType = this.selectedNode[0].type; + if (nodeType !== NodeTypes.Core && nodeType !== NodeTypes.Transfer) {return;} + this.setActionButtonsActive(nodeType); + this.setActionButton(NodeActions.Overflow, false); //Set Overflow button inactive + this.selectedNode.forEach(function(node){ + node.action = NodeActions.Overflow; + }); + }); + + this.actionButtons[5].addEventListener("click", ()=>{ + if (!(this.selectedNode.length > 0)) { + console.log("ERR: Pressing Action button without selected node"); + return; + } + this.selectedNode.forEach(function(node){ + if (node.conn) { + var endpoints = node.conn.endpoints; + endpoints[0].detachFrom(endpoints[1]); + } + node.action = NodeActions.Fortify; + }); + // if (this.selectedNode.conn) { + // var endpoints = this.selectedNode.conn.endpoints; + // endpoints[0].detachFrom(endpoints[1]); + // } + }) + + var timeDisplay = document.createElement("p"); + + container.appendChild(headerText); + container.appendChild(inGameGuideBtn); + container.appendChild(wikiGuideBtn); + container.appendChild(startBtn); + container.appendChild(forfeitMission); + container.appendChild(timer); + container.appendChild(actionsContainer); + container.appendChild(timeDisplay); +} + +HackingMission.prototype.setActionButtonsInactive = function() { + for (var i = 0; i < this.actionButtons.length; ++i) { + this.actionButtons[i].classList.remove("a-link-button"); + this.actionButtons[i].classList.add("a-link-button-inactive"); + } +} + +HackingMission.prototype.setActionButtonsActive = function(nodeType=null) { + for (var i = 0; i < this.actionButtons.length; ++i) { + this.actionButtons[i].classList.add("a-link-button"); + this.actionButtons[i].classList.remove("a-link-button-inactive"); + } + + //For Transfer, FireWall and Shield Nodes, certain buttons should always be disabled + //0 = Attack, 1 = Scan, 2 = Weaken, 3 = Fortify, 4 = overflow, 5 = Drop conn + if (nodeType) { + switch (nodeType) { + case NodeTypes.Firewall: + case NodeTypes.Shield: + this.actionButtons[0].classList.remove("a-link-button"); + this.actionButtons[0].classList.add("a-link-button-inactive"); + this.actionButtons[1].classList.remove("a-link-button"); + this.actionButtons[1].classList.add("a-link-button-inactive"); + this.actionButtons[2].classList.remove("a-link-button"); + this.actionButtons[2].classList.add("a-link-button-inactive"); + this.actionButtons[4].classList.remove("a-link-button"); + this.actionButtons[4].classList.add("a-link-button-inactive"); + this.actionButtons[5].classList.remove("a-link-button"); + this.actionButtons[5].classList.add("a-link-button-inactive"); + break; + case NodeTypes.Transfer: + this.actionButtons[0].classList.remove("a-link-button"); + this.actionButtons[0].classList.add("a-link-button-inactive"); + break; + default: + break; + } + } +} + +//True for active, false for inactive +HackingMission.prototype.setActionButton = function(i, active=true) { + if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(i)) { + switch (i) { + case NodeActions.Attack: + i = 0; + break; + case NodeActions.Scan: + i = 1; + break; + case NodeActions.Weaken: + i = 2; + break; + case NodeActions.Fortify: + i = 3; + break; + case NodeActions.Overflow: + default: + i = 4; + break; + } + } + if (active) { + this.actionButtons[i].classList.remove("a-link-button-inactive"); + this.actionButtons[i].classList.add("a-link-button"); + } else { + this.actionButtons[i].classList.remove("a-link-button"); + this.actionButtons[i].classList.add("a-link-button-inactive"); + } + +} + +HackingMission.prototype.calculateAttacks = function() { + var total = 0; + for (var i = 0; i < this.playerCores.length; ++i) { + total += this.playerCores[i].atk; + } + for (var i = 0; i < this.playerNodes.length; ++i) { + total += this.playerNodes[i].atk; + } + this.playerAtk = total; + document.getElementById("hacking-mission-player-stats").innerHTML = + "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + + "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); + total = 0; + for (var i = 0; i < this.enemyCores.length; ++i) { + total += this.enemyCores[i].atk; + } + for (var i = 0; i < this.enemyDatabases.length; ++i) { + total += this.enemyDatabases[i].atk; + } + for (var i = 0; i < this.enemyNodes.length; ++i) { + total += this.enemyNodes[i].atk; + } + this.enemyAtk = total; + document.getElementById("hacking-mission-enemy-stats").innerHTML = + "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + + "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); +} + +HackingMission.prototype.calculateDefenses = function() { + var total = 0; + for (var i = 0; i < this.playerCores.length; ++i) { + total += this.playerCores[i].def; + } + for (var i = 0; i < this.playerNodes.length; ++i) { + total += this.playerNodes[i].def; + } + this.playerDef = total; + document.getElementById("hacking-mission-player-stats").innerHTML = + "Player Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerAtk, 1) + "
" + + "Player Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.playerDef, 1); + total = 0; + for (var i = 0; i < this.enemyCores.length; ++i) { + total += this.enemyCores[i].def; + } + for (var i = 0; i < this.enemyDatabases.length; ++i) { + total += this.enemyDatabases[i].def; + } + for (var i = 0; i < this.enemyNodes.length; ++i) { + total += this.enemyNodes[i].def; + } + this.enemyDef = total; + document.getElementById("hacking-mission-enemy-stats").innerHTML = + "Enemy Attack: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyAtk, 1) + "
" + + "Enemy Defense: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(this.enemyDef, 1); +} + +HackingMission.prototype.removeAvailablePosition = function(x, y) { + for (var i = 0; i < this.availablePositions.length; ++i) { + if (this.availablePositions[i][0] === x && + this.availablePositions[i][1] === y) { + this.availablePositions.splice(i, 1); + return; + } + } + console.log("WARNING: removeAvailablePosition() did not remove " + x + ", " + y); +} + +HackingMission.prototype.setNodePosition = function(nodeObj, x, y) { + if (!(nodeObj instanceof Node)) { + console.log("WARNING: Non-Node object passed into setNodePOsition"); + return; + } + if (isNaN(x) || isNaN(y)) { + console.log("ERR: Invalid values passed as x and y for setNodePosition"); + console.log(x); + console.log(y); + return; + } + nodeObj.pos = [x, y]; + this.map[x][y] = nodeObj; +} + +HackingMission.prototype.setNodeRandomPosition = function(nodeObj, xlimit=0) { + var i = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.availablePositions.length - 1); + if (this.availablePositions[i][1] < xlimit) { + //Recurse if not within limit + return this.setNodeRandomPosition(nodeObj, xlimit); + } + var pos = this.availablePositions.splice(i, 1); + pos = pos[0]; + this.setNodePosition(nodeObj, pos[0], pos[1]); +} + +HackingMission.prototype.createMap = function() { + //Use a grid + var map = document.createElement("div"); + map.classList.add("hack-mission-grid"); + map.setAttribute("id", "hacking-mission-map"); + document.getElementById("mission-container").appendChild(map); + + //Create random Nodes for every space in the map that + //hasn't been filled yet. The stats of each Node will be based on + //the player/enemy attack + var averageAttack = (this.playerAtk + this.enemyAtk) / 2; + for (var x = 0; x < 8; ++x) { + for (var y = 0; y < 8; ++y) { + if (!(this.map[x][y] instanceof Node)) { + var node, type = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 2); + var randMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["addOffset"])(0.85 + (this.difficulty / 2), 15); + switch (type) { + case 0: //Spam + var stats = { + atk: 0, + def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(200, 225) + } + node = new Node(NodeTypes.Spam, stats); + break; + case 1: //Transfer + var stats = { + atk: 0, + def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(15, 45), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(250, 275) + } + node = new Node(NodeTypes.Transfer, stats); + break; + case 2: //Shield + default: + var stats = { + atk: 0, + def: averageAttack * 1.1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(30, 70), + hp: randMult * Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(300, 320) + } + node = new Node(NodeTypes.Shield, stats); + break; + } + this.setNodePosition(node, x, y); + this.removeAvailablePosition(x, y); + this.miscNodes.push(node); + } + } + } + + //Create DOM elements in order + for (var r = 0; r < 8; ++r) { + for (var c = 0; c < 8; ++c) { + this.createNodeDomElement(this.map[r][c]); + } + } + + //Configure all Player CPUS + for (var i = 0; i < this.playerCores.length; ++i) { + console.log("Configuring Player Node: " + this.playerCores[i].el.id); + this.configurePlayerNodeElement(this.playerCores[i].el); + } +} + +HackingMission.prototype.createNodeDomElement = function(nodeObj) { + var nodeDiv = document.createElement("a"), txtEl = document.createElement('p'); + nodeObj.el = nodeDiv; + + //Set the node element's id based on its coordinates + var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; + nodeDiv.setAttribute("id", id); + txtEl.setAttribute("id", id + "-txt"); + + //Set node classes for owner + nodeDiv.classList.add("hack-mission-node"); + if (nodeObj.plyrCtrl) { + nodeDiv.classList.add("hack-mission-player-node"); + } else if (nodeObj.enmyCtrl) { + nodeDiv.classList.add("hack-mission-enemy-node"); + } + + //Set node classes based on type + var txt; + switch (nodeObj.type) { + case NodeTypes.Core: + txt = "CPU Core
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-cpu-node"); + break; + case NodeTypes.Firewall: + txt = "Firewall
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-firewall-node"); + break; + case NodeTypes.Database: + txt = "Database
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-database-node"); + break; + case NodeTypes.Spam: + txt = "Spam
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-spam-node"); + break; + case NodeTypes.Transfer: + txt = "Transfer
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-transfer-node"); + break; + case NodeTypes.Shield: + default: + txt = "Shield
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + nodeDiv.classList.add("hack-mission-shield-node"); + break; + } + + txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + + "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); + txtEl.innerHTML = txt; + + nodeDiv.appendChild(txtEl); + document.getElementById("hacking-mission-map").appendChild(nodeDiv); +} + +HackingMission.prototype.updateNodeDomElement = function(nodeObj) { + if (nodeObj.el == null) { + console.log("ERR: Calling updateNodeDomElement on a Node without an element"); + return; + } + + var id = "hacking-mission-node-" + nodeObj.pos[0] + "-" + nodeObj.pos[1]; + var nodeDiv = document.getElementById(id), txtEl = document.getElementById(id + "-txt"); + + //Set node classes based on type + var txt; + switch (nodeObj.type) { + case NodeTypes.Core: + txt = "CPU Core
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + case NodeTypes.Firewall: + txt = "Firewall
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + case NodeTypes.Database: + txt = "Database
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + case NodeTypes.Spam: + txt = "Spam
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + case NodeTypes.Transfer: + txt = "Transfer
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + case NodeTypes.Shield: + default: + txt = "Shield
" + "HP: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.hp, 1); + break; + } + + txt += "
Atk: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.atk, 1) + + "
Def: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(nodeObj.def, 1); + if (nodeObj.action) { + txt += "
" + nodeObj.action; + } + txtEl.innerHTML = txt; +} + +//Gets a Node DOM element's corresponding Node object using its +//element id. Function accepts either the DOM element object or the ID as +//an argument +HackingMission.prototype.getNodeFromElement = function(el) { + var id; + if (Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["isString"])(el)) { + id = el; + } else { + id = el.id; + } + id = id.replace("hacking-mission-node-", ""); + var res = id.split('-'); + if (res.length != 2) { + console.log("ERROR Parsing Hacking Mission Node Id. Could not find coordinates"); + return null; + } + var x = res[0], y = res[1]; + if (isNaN(x) || isNaN(y) || x >= 8 || y >= 8 || x < 0 || y < 0) { + console.log("ERROR: Unexpected values for x and y: " + x + ", " + y); + return null; + } + return this.map[x][y]; +} + +function selectNode(hackMissionInst, el) { + var nodeObj = hackMissionInst.getNodeFromElement(el); + if (nodeObj == null) {console.log("Error getting Node object");} + if (!nodeObj.plyrCtrl) {return;} + + clearAllSelectedNodes(hackMissionInst); + nodeObj.select(hackMissionInst.actionButtons); + hackMissionInst.selectedNode.push(nodeObj); +} + +function multiselectNode(hackMissionInst, el) { + var nodeObj = hackMissionInst.getNodeFromElement(el); + if (nodeObj == null) {console.log("ERROR: Getting Node Object in multiselectNode()");} + if (!nodeObj.plyrCtrl) {return;} + + clearAllSelectedNodes(hackMissionInst); + var type = nodeObj.type; + if (type === NodeTypes.Core) { + hackMissionInst.playerCores.forEach(function(node) { + node.select(hackMissionInst.actionButtons); + hackMissionInst.selectedNode.push(node); + }); + } else { + hackMissionInst.playerNodes.forEach(function(node) { + if (node.type === type) { + node.select(hackMissionInst.actionButtons); + hackMissionInst.selectedNode.push(node); + } + }); + } +} + +function clearAllSelectedNodes(hackMissionInst) { + if (hackMissionInst.selectedNode.length > 0) { + hackMissionInst.selectedNode.forEach(function(node){ + node.deselect(hackMissionInst.actionButtons); + }); + hackMissionInst.selectedNode.length = 0; + } +} + +//Configures a DOM element representing a player-owned node to +//be selectable and actionable +//Note: Does NOT change its css class. This is handled by Node.setControlledBy... +HackingMission.prototype.configurePlayerNodeElement = function(el) { + var nodeObj = this.getNodeFromElement(el); + if (nodeObj == null) {console.log("Error getting Node object");} + + //Add event listener + var self = this; + function selectNodeWrapper() { + selectNode(self, el); + } + el.addEventListener("click", selectNodeWrapper); + + function multiselectNodeWrapper() { + multiselectNode(self, el); + } + el.addEventListener("dblclick", multiselectNodeWrapper); + + + if (el.firstChild) { + el.firstChild.addEventListener("click", selectNodeWrapper); + } +} + +//Configures a DOM element representing an enemy-node by removing +//any event listeners +HackingMission.prototype.configureEnemyNodeElement = function(el) { + //Deselect node if it was the selected node + var nodeObj = this.getNodeFromElement(el); + for (var i = 0; i < this.selectedNode.length; ++i) { + if (this.selectedNode[i] == nodeObj) { + nodeObj.deselect(this.actionButtons); + this.selectedNode.splice(i, 1); + break; + } + } +} + +//Returns bool indicating whether a node is reachable by player +//by checking if any of the adjacent nodes are owned by the player +HackingMission.prototype.nodeReachable = function(node) { + var x = node.pos[0], y = node.pos[1]; + if (x > 0 && this.map[x-1][y].plyrCtrl) {return true;} + if (x < 7 && this.map[x+1][y].plyrCtrl) {return true;} + if (y > 0 && this.map[x][y-1].plyrCtrl) {return true;} + if (y < 7 && this.map[x][y+1].plyrCtrl) {return true;} + return false; +} + +HackingMission.prototype.nodeReachableByEnemy = function(node) { + if (node == null) {return false;} + var x = node.pos[0], y = node.pos[1]; + if (x > 0 && this.map[x-1][y].enmyCtrl) {return true;} + if (x < 7 && this.map[x+1][y].enmyCtrl) {return true;} + if (y > 0 && this.map[x][y-1].enmyCtrl) {return true;} + if (y < 7 && this.map[x][y+1].enmyCtrl) {return true;} + return false; +} + +HackingMission.prototype.start = function() { + this.started = true; + this.initJsPlumb(); + var startBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("hack-mission-start-btn"); + startBtn.classList.remove("a-link-button"); + startBtn.classList.add("a-link-button-inactive"); +} + +HackingMission.prototype.initJsPlumb = function() { + var instance = jsPlumb.getInstance({ + DragOptions:{cursor:"pointer", zIndex:2000}, + PaintStyle: { + gradient: { stops: [ + [ 0, "#FFFFFF" ], + [ 1, "#FFFFFF" ] + ] }, + stroke: "#FFFFFF", + strokeWidth: 8 + }, + }); + + this.jsplumbinstance = instance; + + //All player cores are sources + for (var i = 0; i < this.playerCores.length; ++i) { + instance.makeSource(this.playerCores[i].el, { + deleteEndpointsOnEmpty:true, + maxConnections:1, + anchor:"Continuous", + connector:"Flowchart" + }); + } + + //Everything else is a target + for (var i = 0; i < this.enemyCores.length; ++i) { + instance.makeTarget(this.enemyCores[i].el, { + maxConnections:-1, + anchor:"Continuous", + connector:"Flowchart" + }); + } + for (var i = 0; i < this.enemyDatabases.length; ++i) { + instance.makeTarget(this.enemyDatabases[i].el, { + maxConnections:-1, + anchor:"Continuous", + connector:["Flowchart"] + }); + } + for (var i = 0; i < this.enemyNodes.length; ++i) { + instance.makeTarget(this.enemyNodes[i].el, { + maxConnections:-1, + anchor:"Continuous", + connector:"Flowchart" + }); + } + for (var i = 0; i < this.miscNodes.length; ++i) { + instance.makeTarget(this.miscNodes[i].el, { + maxConnections:-1, + anchor:"Continuous", + connector:"Flowchart" + }); + } + + //Clicking a connection drops it + instance.bind("click", function(conn, originalEvent) { + var endpoints = conn.endpoints; + endpoints[0].detachFrom(endpoints[1]); + }); + + //Connection events + instance.bind("connection", (info)=>{ + var targetNode = this.getNodeFromElement(info.target); + + //Do not detach for enemy nodes + var thisNode = this.getNodeFromElement(info.source); + if (thisNode.enmyCtrl) {return;} + + //If the node is not reachable, drop the connection + if (!this.nodeReachable(targetNode)) { + info.sourceEndpoint.detachFrom(info.targetEndpoint); + return; + } + + var sourceNode = this.getNodeFromElement(info.source); + sourceNode.conn = info.connection; + var targetNode = this.getNodeFromElement(info.target); + ++targetNode.targetedCount; + }); + + //Detach Connection events + instance.bind("connectionDetached", (info, originalEvent)=>{ + var sourceNode = this.getNodeFromElement(info.source); + sourceNode.conn = null; + var targetNode = this.getNodeFromElement(info.target); + targetNode.untarget(); + }); + +} + +//Drops all connections where the specified node is the source +HackingMission.prototype.dropAllConnectionsFromNode = function(node) { + var allConns = this.jsplumbinstance.getAllConnections(); + for (var i = allConns.length-1; i >= 0; --i) { + if (allConns[i].source == node.el) { + allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); + } + } +} + +//Drops all connections where the specified node is the target +HackingMission.prototype.dropAllConnectionsToNode = function(node) { + var allConns = this.jsplumbinstance.getAllConnections(); + for (var i = allConns.length-1; i >= 0; --i) { + if (allConns[i].target == node.el) { + allConns[i].endpoints[0].detachFrom(allConns[i].endpoints[1]); + } + } + node.beingTargeted = false; +} + +var storedCycles = 0; +HackingMission.prototype.process = function(numCycles=1) { + if (!this.started) {return;} + storedCycles += numCycles; + if (storedCycles < 2) {return;} //Only process every 3 cycles minimum + + var res = false; + //Process actions of all player nodes + this.playerCores.forEach((node)=>{ + res |= this.processNode(node, storedCycles); + }); + + this.playerNodes.forEach((node)=>{ + if (node.type === NodeTypes.Transfer || + node.type === NodeTypes.Shield || + node.type === NodeTypes.Firewall) { + res |= this.processNode(node, storedCycles); + } + }); + + //Process actions of all enemy nodes + this.enemyCores.forEach((node)=>{ + this.enemyAISelectAction(node); + res |= this.processNode(node, storedCycles); + }); + + this.enemyNodes.forEach((node)=>{ + if (node.type === NodeTypes.Transfer || + node.type === NodeTypes.Shield || + node.type === NodeTypes.Firewall) { + this.enemyAISelectAction(node); + res |= this.processNode(node, storedCycles); + } + }); + + //The hp of enemy databases increases slowly + this.enemyDatabases.forEach((node)=>{ + node.maxhp += (0.1 * storedCycles); + node.hp += (0.1 * storedCycles); + }); + + if (res) { + this.calculateAttacks(); + this.calculateDefenses(); + } + + //Win if all enemy databases are conquered + if (this.enemyDatabases.length === 0) { + this.finishMission(true); + return; + } + + //Lose if all your cores are gone + if (this.playerCores.length === 0) { + this.finishMission(false); + return; + } + + //Defense/hp of misc nodes increases slowly over time + this.miscNodes.forEach((node)=>{ + node.def += (0.1 * storedCycles); + node.maxhp += (0.05 * storedCycles); + node.hp += (0.1 * storedCycles); + if (node.hp > node.maxhp) {node.hp = node.maxhp;} + this.updateNodeDomElement(node); + }); + + //Update timer and check if player lost + this.time -= (storedCycles * _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"]._idleSpeed); + if (this.time <= 0) { + this.finishMission(false); + return; + } + this.updateTimer(); + + storedCycles = 0; +} + +//Returns a bool representing whether defenses need to be re-calculated +HackingMission.prototype.processNode = function(nodeObj, numCycles=1) { + if (nodeObj.action == null) { + return; + } + + var targetNode = null, def, atk; + if (nodeObj.conn) { + if (nodeObj.conn.target != null) { + targetNode = this.getNodeFromElement(nodeObj.conn.target); + } else { + targetNode = this.getNodeFromElement(nodeObj.conn.targetId); + } + + if (targetNode == null) { + //Player is in the middle of dragging the connection, + //so the target node is null. Do nothing here + } else if (targetNode.plyrCtrl) { + def = this.playerDef; + atk = this.enemyAtk; + } else if (targetNode.enmyCtrl) { + def = this.enemyDef; + atk = this.playerAtk; + } else { //Misc Node + def = targetNode.def; + nodeObj.plyrCtrl ? atk = this.playerAtk : atk = this.enemyAtk; + } + } + + //Calculations are per second, so divide everything by 5 + var calcStats = false, plyr = nodeObj.plyrCtrl; + var enmyHacking = this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionDifficultyToHacking; + switch(nodeObj.action) { + case NodeActions.Attack: + if (targetNode == null) {break;} + if (nodeObj.conn == null) {break;} + var dmg = this.calculateAttackDamage(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); + targetNode.hp -= (dmg/5 * numCycles); + break; + case NodeActions.Scan: + if (targetNode == null) {break;} + if (nodeObj.conn == null) {break;} + var eff = this.calculateScanEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); + targetNode.def -= (eff/5 * numCycles); + calcStats = true; + break; + case NodeActions.Weaken: + if (targetNode == null) {break;} + if (nodeObj.conn == null) {break;} + var eff = this.calculateWeakenEffect(atk, def, plyr ? _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill : enmyHacking); + targetNode.atk -= (eff/5 * numCycles); + calcStats = true; + break; + case NodeActions.Fortify: + var eff = this.calculateFortifyEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); + nodeObj.def += (eff/5 * numCycles); + calcStats = true; + break; + case NodeActions.Overflow: + var eff = this.calculateOverflowEffect(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill); + if (nodeObj.def < eff) {break;} + nodeObj.def -= (eff/5 * numCycles); + nodeObj.atk += (eff/5 * numCycles); + calcStats = true; + break; + default: + console.log("ERR: Invalid Node Action: " + nodeObj.action); + break; + } + + //Stats can't go below 0 + if (nodeObj.atk < 0) {nodeObj.atk = 0;} + if (nodeObj.def < 0) {nodeObj.def = 0;} + if (targetNode && targetNode.atk < 0) {targetNode.atk = 0;} + if (targetNode && targetNode.def < 0) {targetNode.def = 0;} + + //Conquering a node + if (targetNode && targetNode.hp <= 0) { + var conqueredByPlayer = nodeObj.plyrCtrl; + targetNode.hp = targetNode.maxhp; + targetNode.action = null; + targetNode.conn = null; + if (this.selectedNode == targetNode) { + targetNode.deselect(this.actionButtons); + } + + //The conquered node has its stats reduced + targetNode.atk /= 2; + targetNode.def /= 3.5; + + //Flag for whether the target node was a misc node + var isMiscNode = !targetNode.plyrCtrl && !targetNode.enmyCtrl; + + //Remove all connections from Node + this.dropAllConnectionsToNode(targetNode); + this.dropAllConnectionsFromNode(targetNode); + + //Changes the css class and turn the node into a JsPlumb Source/Target + if (conqueredByPlayer) { + targetNode.setControlledByPlayer(); + this.jsplumbinstance.unmakeTarget(targetNode.el); + this.jsplumbinstance.makeSource(targetNode.el, { + deleteEndpointsOnEmpty:true, + maxConnections:1, + anchor:"Continuous", + connector:"Flowchart" + }); + } else { + targetNode.setControlledByEnemy(); + nodeObj.conn = null; //Clear connection + this.jsplumbinstance.unmakeSource(targetNode.el); + this.jsplumbinstance.makeTarget(targetNode.el, { + maxConnections:-1, + anchor:"Continuous", + connector:["Flowchart"] + }); + } + + calcStats = true; + + //Helper function to swap nodes between the respective enemyNodes/playerNodes arrays + function swapNodes(orig, dest, targetNode) { + for (var i = 0; i < orig.length; ++i) { + if (orig[i] == targetNode) { + var node = orig.splice(i, 1); + node = node[0]; + dest.push(node); + break; + } + } + } + + switch(targetNode.type) { + case NodeTypes.Core: + if (conqueredByPlayer) { + swapNodes(this.enemyCores, this.playerCores, targetNode); + this.configurePlayerNodeElement(targetNode.el); + } else { + swapNodes(this.playerCores, this.enemyCores, targetNode); + this.configureEnemyNodeElement(targetNode.el); + } + break; + case NodeTypes.Firewall: + if (conqueredByPlayer) { + swapNodes(this.enemyNodes, this.playerNodes, targetNode); + } else { + swapNodes(this.playerNodes, this.enemyNodes, targetNode); + this.configureEnemyNodeElement(targetNode.el); + } + break; + case NodeTypes.Database: + if (conqueredByPlayer) { + swapNodes(this.enemyDatabases, this.playerNodes, targetNode); + } else { + swapNodes(this.playerNodes, this.enemyDatabases, targetNode); + } + break; + case NodeTypes.Spam: + if (conqueredByPlayer) { + swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); + //Conquering spam node increases time limit + this.time += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionSpamTimeIncrease; + } else { + swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); + } + + break; + case NodeTypes.Transfer: + //Conquering a Transfer node increases the attack of all cores by some percentages + if (conqueredByPlayer) { + swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); + this.playerCores.forEach(function(node) { + node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; + }); + this.configurePlayerNodeElement(targetNode.el); + } else { + swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); + this.enemyCores.forEach(function(node) { + node.atk *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionTransferAttackIncrease; + }); + this.configureEnemyNodeElement(targetNode.el); + } + break; + case NodeTypes.Shield: + if (conqueredByPlayer) { + swapNodes(isMiscNode ? this.miscNodes : this.enemyNodes, this.playerNodes, targetNode); + this.configurePlayerNodeElement(targetNode.el); + } else { + swapNodes(isMiscNode ? this.miscNodes : this.playerNodes, this.enemyNodes, targetNode); + this.configureEnemyNodeElement(targetNode.el); + } + break; + } + + //If a misc node was conquered, the defense for all misc nodes increases by some fixed amount + if (isMiscNode) { //&& conqueredByPlayer) { + this.miscNodes.forEach((node)=>{ + if (node.targetedCount === 0) { + node.def *= _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HackingMissionMiscDefenseIncrease; + } + }); + } + } + + //Update node DOMs + this.updateNodeDomElement(nodeObj); + if (targetNode) {this.updateNodeDomElement(targetNode);} + return calcStats; +} + +//Enemy "AI" for CPU Core and Transfer Nodes +HackingMission.prototype.enemyAISelectAction = function(nodeObj) { + if (nodeObj == null) {return;} + switch(nodeObj.type) { + case NodeTypes.Core: + //Select a single RANDOM target from miscNodes and player's Nodes + //If it is reachable, it will target it. If not, no target will + //be selected for now, and the next time process() gets called this will repeat + if (nodeObj.conn == null) { + if (this.miscNodes.length === 0) { + //Randomly pick a player node and attack it if its reachable + var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerNodes.length-1); + var node; + if (this.playerNodes.length === 0) { + node = null; + } else { + node = this.playerNodes[rand]; + } + if (this.nodeReachableByEnemy(node)) { + //Create connection + nodeObj.conn = this.jsplumbinstance.connect({ + source:nodeObj.el, + target:node.el + }); + ++node.targetedCount; + } else { + //Randomly pick a player core and attack it if its reachable + rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.playerCores.length-1); + if (this.playerCores.length === 0) { + return; //No Misc Nodes, no player Nodes, no Player cores. Player lost + } else { + node = this.playerCores[rand]; + } + + if (this.nodeReachableByEnemy(node)) { + //Create connection + nodeObj.conn = this.jsplumbinstance.connect({ + source:nodeObj.el, + target:node.el + }); + ++node.targetedCount; + } + } + } else { + //Randomly pick a misc node and attack it if its reachable + var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, this.miscNodes.length-1); + var node = this.miscNodes[rand]; + if (this.nodeReachableByEnemy(node)) { + nodeObj.conn = this.jsplumbinstance.connect({ + source:nodeObj.el, + target:node.el, + }); + ++node.targetedCount; + } + } + + //If no connection was made, set the Core to Fortify + nodeObj.action = NodeActions.Fortify; + } else { + //If this node has a selected target + var targetNode; + if (nodeObj.conn.target) { + targetNode = this.getNodeFromElement(nodeObj.conn.target); + } else { + targetNode = this.getNodeFromElement(nodeObj.conn.targetId); + } + if (targetNode == null) { + console.log("Error getting Target node Object in enemyAISelectAction()"); + } + + if (targetNode.def > this.enemyAtk + 15) { + if (nodeObj.def < 50) { + nodeObj.action = NodeActions.Fortify; + } else { + nodeObj.action = NodeActions.Overflow; + } + } else if (Math.abs(targetNode.def - this.enemyAtk) <= 15) { + nodeObj.action = NodeActions.Scan; + } else { + nodeObj.action = NodeActions.Attack; + } + } + break; + case NodeTypes.Transfer: + //Switch between fortifying and overflowing as necessary + if (nodeObj.def < 125) { + nodeObj.action = NodeActions.Fortify; + } else { + nodeObj.action = NodeActions.Overflow; + } + break; + case NodeTypes.Firewall: + case NodeTypes.Shield: + nodeObj.action = NodeActions.Fortify; + break; + default: + break; + } +} + +var hackEffWeightSelf = 130; //Weight for Node actions on self +var hackEffWeightTarget = 25; //Weight for Node Actions against Target +var hackEffWeightAttack = 80; //Weight for Attack action + +//Returns damage per cycle based on stats +HackingMission.prototype.calculateAttackDamage = function(atk, def, hacking = 0) { + return Math.max(0.55 * (atk + (hacking / hackEffWeightAttack) - def), 1); +} + +HackingMission.prototype.calculateScanEffect = function(atk, def, hacking=0) { + return Math.max(0.6 * ((atk) + hacking / hackEffWeightTarget - (def * 0.95)), 2); +} + +HackingMission.prototype.calculateWeakenEffect = function(atk, def, hacking=0) { + return Math.max((atk) + hacking / hackEffWeightTarget - (def * 0.95), 2); +} + +HackingMission.prototype.calculateFortifyEffect = function(hacking=0) { + return 0.9 * hacking / hackEffWeightSelf; +} + +HackingMission.prototype.calculateOverflowEffect = function(hacking=0) { + return 0.95 * hacking / hackEffWeightSelf; +} + +//Updates timer display +HackingMission.prototype.updateTimer = function() { + var timer = document.getElementById("hacking-mission-timer"); + + //Convert time remaining to a string of the form mm:ss + var seconds = Math.round(this.time / 1000); + var minutes = Math.trunc(seconds / 60); + seconds %= 60; + var str = ("0" + minutes).slice(-2) + ":" + ("0" + seconds).slice(-2); + timer.innerText = "Time left: " + str; +} + +//The 'win' argument is a bool for whether or not the player won +HackingMission.prototype.finishMission = function(win) { + inMission = false; + currMission = null; + + if (win) { + var favorMult = 1 + (this.faction.favor / 100); + console.log("Hacking mission base reward: " + this.reward); + console.log("favorMult: " + favorMult); + console.log("rep mult: " + _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult); + var gain = this.reward * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult * favorMult; + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission won! You earned " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(gain, 3) + " reputation with " + this.faction.name); + _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gainIntelligenceExp(this.difficulty * _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].IntelligenceHackingMissionBaseExpGain); + this.faction.playerReputation += gain; + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Mission lost/forfeited! You did not gain any faction reputation."); + } + + //Clear mission container + var container = document.getElementById("mission-container"); + while(container.firstChild) { + container.removeChild(container.firstChild); + } + + //Return to Faction page + document.getElementById("mainmenu-container").style.visibility = "visible"; + document.getElementById("character-overview-wrapper").style.visibility = "visible"; + _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); + Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(this.faction.name); +} + + + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) + +/***/ }), +/* 40 */ +/*!****************************!*\ + !*** ./src/Bladeburner.js ***! + \****************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bladeburner", function() { return Bladeburner; }); +/* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Location.js */ 4); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./RedPill.js */ 41); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10__); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); + + + + + + + + + + + + + + + +var CityNames = ["Aevum", "Chongqing", "Sector-12", "New Tokyo", "Ishima", "Volhaven"]; + +var CyclesPerSecond = 5; //Game cycle is 200 ms + +var StaminaGainPerSecond = 0.0085; +var BaseStaminaLoss = 0.285; //Base stamina loss per action. Increased based on difficulty +var MaxStaminaToGainFactor = 70000; //Max Stamina is divided by this to get bonus stamina gain + +var DifficultyToTimeFactor = 10; //Action Difficulty divided by this to get base action time + +//The difficulty multiplier affects stamina loss and hp loss of an action. Its formula is: +//difficulty ^ exponentialFactor + difficulty / linearFactor +var DiffMultExponentialFactor = 0.28; +var DiffMultLinearFactor = 670; + +var BaseRecruitmentTimeNeeded = 300; //Base time needed (s) to complete a Recruitment action + +var PopulationThreshold = 1e9; //Population at which success rates start being affected +var ChaosThreshold = 50; //City chaos level after which it starts making tasks harder + +var BaseStatGain = 1; //Base stat gain per second +var BaseIntGain = 0.001; //Base intelligence stat gain + +var ActionCountGrowthPeriod = 300; //Time (s) it takes for action count to grow by its specified value + +var RankToFactionRepFactor = 2; //Delta Faction Rep = this * Delta Rank + +var ContractSuccessesPerLevel = 15; //How many successes you need to level up a contract +var OperationSuccessesPerLevel = 10; //How many successes you need to level up an op + +var RanksPerSkillPoint = 4; //How many ranks needed to get 1 Skill Point + +var ContractBaseMoneyGain = 5e3; //Base Money Gained per contract + +//DOM related variables +var ActiveActionCssClass = "bladeburner-active-action"; + +//Console related stuff +var consoleHistory = []; //Console command history +var consoleHistoryIndex = 0; +var consoleHelpText = { + helpList:"Use 'help [command]' to get more information about a particular Bladeburner console command.

" + + "automate [var] [val] [hi/low] Configure simple automation for Bladeburner tasks
" + + "clear/cls Clear the console
" + + "help [cmd] Display this help text, or help text for a specific command
" + + "log [en/dis] [type] Enable or disable logging for events and actions
" + + "skill [action] [name] Level or display info about your Bladeburner skills
" + + "start [type] [name] Start a Bladeburner action/task
" + + "stop Stops your current Bladeburner action/task
", + automate:"automate [var] [val] [hi/low]

" + + "A simple way to automate your Bladeburner actions. This console command can be used " + + "to automatically start an action when your stamina rises above a certain threshold, and " + + "automatically switch to another action when your stamina drops below another threshold.

" + + "automate status - Check the current status of your automation and get a brief description of what it'll do
" + + "automate en - Enable the automation feature
" + + "automate dis - Disable the automation feature

" + + "There are four properties that must be set for this automation to work properly. Here is how to set them:

" + + "automate stamina 100 high
" + + "automate contract Tracking high
" + + "automate stamina 50 low
" + + 'automate general "Field Analysis" low

' + + "Using the four console commands above will set the automation to perform Tracking contracts " + + "if your stamina is 100 or higher, and then switch to Field Analysis if your stamina drops below " + + "50. Note that when setting the action, the name of the action is CASE-SENSITIVE. It must " + + "exactly match whatever the name is in the UI.", + clear:"clear

Clears the console", + cls:"cls

Clears the console", + help:"help [command]

" + + "Running 'help' with no arguments displays the general help text, which lists all console commands " + + "and a brief description of what they do. A command can be specified to get more specific help text " + + "about that particular command. For example:

" + + "help automate

" + + "will display specific information about using the automate console command", + log:"log [en/dis] [type]

" + + "Enable or disable logging. By default, the results of completing actions such as contracts/operations are logged " + + "in the console. There are also random events that are logged in the console as well. The five categories of " + + "things that get logged are:

" + + "[general, contracts, ops, blackops, events]

" + + "The logging for these categories can be enabled or disabled like so:

" + + "log dis contracts - Disables logging that occurs when contracts are completed
" + + "log en contracts - Enables logging that occurs when contracts are completed
" + + "log dis events - Disables logging for Bladeburner random events

" + + "Logging can be universally enabled/disabled using the 'all' keyword:

" + + "log dis all
" + + "log en all", + skill:"skill [action] [name]

" + + "Level or display information about your skills.

" + + "To display information about all of your skills and your multipliers, use:

" + + "skill list

" + + "To display information about a specific skill, specify the name of the skill afterwards. " + + "Note that the name of the skill is case-sensitive. Enter it exactly as seen in the UI. If " + + "the name of the skill has whitespace, enclose the name of the skill in double quotation marks:

" + + "skill list Reaper
" + + 'skill list "Digital Observer"

' + + "This console command can also be used to level up skills:

" + + "skill level [skill name]", + start:"start [type] [name]

" + + "Start an action. An action is specified by its type and its name. The " + + "name is case-sensitive. It must appear exactly as it does in the UI. If " + + "the name of the action has whitespace, enclose it in double quotation marks. " + + "Valid action types include:

" + + "[general, contract, op, blackop]

" + + "Examples:

" + + 'start contract Tracking
' + + 'start op "Undercover Operation"
', + stop:"stop

" + + "Stop your current action and go idle", +} + +//Keypresses for Console +$(document).keydown(function(event) { + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { + //if (DomElems.consoleInput && !event.ctrlKey && !event.shiftKey && !event.altKey) { + // DomElems.consoleInput.focus(); + //} + + if (!(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner instanceof Bladeburner)) {return;} + + //NOTE: Keycodes imported from Terminal.js + if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].ENTER) { + event.preventDefault(); + var command = DomElems.consoleInput.value; + if (command.length > 0) { + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.postToConsole("> " + command); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.resetConsoleInput(); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner.executeConsoleCommands(command); + } + } + + if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].UPARROW) { + if (DomElems.consoleInput == null) {return;} + var i = consoleHistoryIndex; + var len = consoleHistory.length; + + if (len === 0) {return;} + if (i < 0 || i > len) { + consoleHistoryIndex = len; + } + + if (i !== 0) { + --consoleHistoryIndex; + } + + var prevCommand = consoleHistory[consoleHistoryIndex]; + DomElems.consoleInput.value = prevCommand; + setTimeout(function(){DomElems.consoleInput.selectionStart = DomElems.consoleInput.selectionEnd = 10000; }, 0); + } + + if (event.keyCode === _Terminal_js__WEBPACK_IMPORTED_MODULE_6__["KEY"].DOWNARROW) { + if (DomElems.consoleInput == null) {return;} + var i = consoleHistoryIndex; + var len = consoleHistory.length; + + if (len == 0) {return;} + if (i < 0 || i > len) { + consoleHistoryIndex = len; + } + + //Latest command, put nothing + if (i == len || i == len-1) { + consoleHistoryIndex = len; + DomElems.consoleInput.value = ""; + } else { + ++consoleHistoryIndex; + var prevCommand = consoleHistory[consoleHistoryIndex]; + DomElems.consoleInput.value = prevCommand; + } + } + } +}); + +function City(params={}) { + this.name = params.name ? params.name : _Location_js__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12; + + //Synthoid population and estimate + this.pop = params.pop ? params.pop : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(800e6, 1.2*PopulationThreshold); + this.popEst = this.pop * (Math.random() + 0.5); + + //Number of Synthoid communities population and estimate + this.comms = params.comms ? params.comms : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 40); + this.commsEst = this.comms + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-2, 2); + if (this.commsEst < 0) {this.commsEst = 0;} + this.chaos = 0; +} + +City.prototype.improvePopulationEstimateByCount = function(n) { + if (isNaN(n)) {throw new Error("NaN passeed into City.improvePopulationEstimateByCount()");} + if (this.popEst < this.pop) { + this.popEst += n; + if (this.popEst > this.pop) {this.popEst = this.pop;} + } else if (this.popEst > this.pop) { + this.popEst -= n; + if (this.popEst < this.pop) {this.popEst = this.pop;} + } +} + +//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5% +City.prototype.improvePopulationEstimateByPercentage = function(p, skillMult=1) { + p = p*skillMult; + if (isNaN(p)) {throw new Error("NaN passed into City.improvePopulationEstimateByPercentage()");} + if (this.popEst < this.pop) { + ++this.popEst; //In case estimate is 0 + this.popEst *= (1 + (p/100)); + if (this.popEst > this.pop) {this.popEst = this.pop;} + } else if (this.popEst > this.pop) { + this.popEst *= (1 - (p/100)); + if (this.popEst < this.pop) {this.popEst = this.pop;} + } +} + +City.prototype.improveCommunityEstimate = function(n=1) { + if (isNaN(n)) {throw new Error("NaN passed into City.improveCommunityEstimate()");} + if (this.commsEst < this.comms) { + this.commsEst += n; + if (this.commsEst > this.comms) {this.commsEst = this.comms;} + } else if (this.commsEst > this.comms) { + this.commsEst -= n; + if (this.commsEst < this.comms) {this.commsEst = this.comms;} + } +} + +//@params options: +// estChange(int): How much the estimate should change by +// estOffset(int): Add offset to estimate (offset by percentage) +City.prototype.changePopulationByCount = function(n, params={}) { + if (isNaN(n)) {throw new Error("NaN passed into City.changePopulationByCount()");} + this.pop += n; + if (params.estChange && !isNaN(params.estChange)) {this.popEst += params.estChange;} + if (params.estOffset) { + this.popEst = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(this.popEst, params.estOffset); + } + this.popEst = Math.max(this.popEst, 0); +} + +//@p is the percentage, not the multiplier. e.g. pass in p = 5 for 5% +//@params options: +// changeEstEqually(bool) - Change the population estimate by an equal amount +// nonZero (bool) - Set to true to ensure that population always changes by at least 1 +City.prototype.changePopulationByPercentage = function(p, params={}) { + if (isNaN(p)) {throw new Error("NaN passed into City.changePopulationByPercentage()");} + if (p === 0) {return;} + var change = Math.round(this.pop * (p/100)); + + //Population always changes by at least 1 + if (params.nonZero && change === 0) { + p > 0 ? change = 1 : change = -1; + } + + this.pop += change; + if (params.changeEstEqually) { + this.popEst += change; + if (this.popEst < 0) {this.popEst = 0;} + } + return change; +} + +City.prototype.changeChaosByCount = function(n) { + if (isNaN(n)) {throw new Error("NaN passed into City.changeChaosByCount()");} + if (n === 0) {return;} + this.chaos += n; + if (this.chaos < 0) {this.chaos = 0;} +} + +//@p is the percentage, not the multiplier (e.g. pass in p = 5 for 5%) +City.prototype.changeChaosByPercentage = function(p) { + if (isNaN(p)) {throw new Error("NaN passed into City.chaosChaosByPercentage()");} + if (p === 0) {return;} + var change = this.chaos * (p/100); + this.chaos += change; + if (this.chaos < 0) {this.chaos = 0;} +} + +City.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("City", this); +} +City.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(City, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.City = City; + +function Skill(params={name:"foo", desc:"foo"}) { + if (params.name) { + this.name = params.name; + } else { + throw new Error("Failed to initialize Bladeburner Skill. No name was specified in ctor"); + } + if (params.desc) { + this.desc = params.desc; + } else { + throw new Error("Failed to initialize Bladeburner Skills. No desc was specified in ctor"); + } + this.baseCost = params.baseCost ? params.baseCost : 1; //Cost is in Skill Points + this.costInc = params.costInc ? params.costInc : 1; //Additive cost increase per level + + if (params.maxLvl) {this.maxLvl = params.maxLvl;} + + //These benefits are additive. So total multiplier will be level (handled externally) times the + //effects below + if (params.successChanceAll) {this.successChanceAll = params.successChanceAll;} + if (params.successChanceStealth) {this.successChanceStealth = params.successChanceStealth;} + if (params.successChanceKill) {this.successChanceKill = params.successChanceKill;} + if (params.successChanceContract) {this.successChanceContract = params.successChanceContract;} + if (params.successChanceOperation) {this.successChanceOperation = params.successChanceOperation;} + + //This multiplier affects everything that increases synthoid population/community estimate + //e.g. Field analysis, Investigation Op, Undercover Op + if (params.successChanceEstimate) {this.successChanceEstimate = params.successChanceEstimate;} + + if (params.actionTime) {this.actionTime = params.actionTime;} + if (params.effHack) {this.effHack = params.effHack;} + if (params.effStr) {this.effStr = params.effStr;} + if (params.effDef) {this.effDef = params.effDef;} + if (params.effDex) {this.effDex = params.effDex;} + if (params.effAgi) {this.effAgi = params.effAgi;} + if (params.effCha) {this.effCha = params.effCha;} + + if (params.stamina) {this.stamina = params.stamina;} + + //Equipment + if (params.weaponAbility) {this.weaponAbility = params.weaponAbility;} + if (params.gunAbility) {this.gunAbility = params.gunAbility;} +} +var Skills = {}; +var SkillNames = { + BladesIntuition: "Blade's Intuition", + Reaper: "Reaper", + Cloak: "Cloak", + Marksman: "Marksman", + WeaponProficiency: "Weapon Proficiency", + Overclock: "Overclock", + EvasiveSystem: "Evasive System", + ShortCircuit: "Short-Circuit", + DigitalObserver: "Digital Observer", + Datamancer: "Datamancer", + Tracer: "Tracer", + CybersEdge: "Cyber's Edge" +} + +//Base Class for Contracts, Operations, and BlackOps +function Action(params={}) { + this.name = params.name ? params.name : ""; + this.desc = params.desc ? params.desc : ""; + + //Difficulty scales with level + //Exact formula is not set in stone + //Initial design: baseDifficulty * (difficultyFac ^ level)? + //difficulty Fac is slightly greater than 1 + this.level = 1; + this.maxLevel = 1; + this.autoLevel = true; + this.baseDifficulty = params.baseDifficulty ? Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(params.baseDifficulty, 10) : 100; + this.difficultyFac = params.difficultyFac ? params.difficultyFac : 1.01; + + //Rank increase/decrease is affected by this exponent + this.rewardFac = params.rewardFac ? params.rewardFac : 1.02; + + this.successes = 0; + this.failures = 0; + + //All of these scale with level/difficulty + this.rankGain = params.rankGain ? params.rankGain : 0; + if (params.rankLoss) {this.rankLoss = params.rankLoss;} + if (params.hpLoss) { + this.hpLoss = params.hpLoss; + this.hpLost = 0; + } + + //Action Category. Current categories are stealth and kill + this.isStealth = params.isStealth ? true : false; + this.isKill = params.isKill ? true : false; + + //Number of this contract remaining, and its growth rate + //Growth rate is an integer and the count will increase by that integer every "cycle" + this.count = params.count ? params.count : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1e3, 25e3); + this.countGrowth = params.countGrowth ? params.countGrowth : Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5); + + //Weighting of each stat in determining action success rate + var defaultWeights = {hack:1/7,str:1/7,def:1/7,dex:1/7,agi:1/7,cha:1/7,int:1/7}; + this.weights = params.weights ? params.weights : defaultWeights; + + //Check to make sure weights are summed properly + var sum = 0; + for (var weight in this.weights) { + if (this.weights.hasOwnProperty(weight)) { + sum += this.weights[weight]; + } + } + if (sum - 1 >= 10 * Number.EPSILON) { + throw new Error("Invalid weights when constructing Action " + this.name + + ". The weights should sum up to 1. They sum up to :" + 1); + } + + //Diminishing returns of stats (stat ^ decay where 0 <= decay <= 1) + var defaultDecays = {hack:0.9,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.9,int:0.9}; + this.decays = params.decays ? params.decays : defaultDecays; + for (var decay in this.decays) { + if (this.decays.hasOwnProperty(decay)) { + if (this.decays[decay] > 1) { + throw new Error("Invalid decays when constructing " + + "Action " + this.name + ". " + + "Decay value cannot be greater than 1"); + } + } + } +} + +Action.prototype.getDifficulty = function() { + var difficulty = this.baseDifficulty * Math.pow(this.difficultyFac, this.level-1); + if (isNaN(difficulty)) {throw new Error("Calculated NaN in Action.getDifficulty()");} + return difficulty; +} + +//@inst - Bladeburner Object +//@params - options: +// est (bool): Get success chance estimate instead of real success chance +Action.prototype.getSuccessChance = function(inst, params={}) { + if (inst == null) {throw new Error("Invalid Bladeburner instance passed into Action.getSuccessChance");} + var difficulty = this.getDifficulty(); + var competence = 0; + for (var stat in this.weights) { + if (this.weights.hasOwnProperty(stat)) { + var playerStatLvl = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].queryStatFromString(stat); + var key = "eff" + stat.charAt(0).toUpperCase() + stat.slice(1); + var effMultiplier = inst.skillMultipliers[key]; + if (effMultiplier == null) { + console.log("ERROR: Failed to find Bladeburner Skill multiplier for: " + stat); + effMultiplier = 1; + } + competence += (this.weights[stat] * Math.pow(effMultiplier*playerStatLvl, this.decays[stat])); + } + } + competence *= inst.calculateStaminaPenalty(); + + //For Operations, factor in team members + if (this instanceof Operation || this instanceof BlackOperation) { + if (this.teamCount && this.teamCount > 0) { + this.teamCount = Math.min(this.teamCount, inst.teamSize); + var teamMultiplier = Math.pow(this.teamCount, 0.05); + competence *= teamMultiplier; + } + } + + //Lower city population results in lower chances + if (!(this instanceof BlackOperation)) { + var city = inst.getCurrentCity(); + if (params.est) { + competence *= (city.popEst / PopulationThreshold); + } else { + competence *= (city.pop / PopulationThreshold); + } + + //Too high of a chaos results in lower chances + if (city.chaos > ChaosThreshold) { + var diff = 1 + (city.chaos - ChaosThreshold); + var mult = Math.pow(diff, 0.1); + difficulty *= mult; + } + + //For Raid Operations, no communities = fail + if (this instanceof Operation && this.name === "Raid") { + if (city.comms <= 0) {return 0;} + } + } + + //Factor skill multipliers into success chance + competence *= inst.skillMultipliers.successChanceAll; + if (this instanceof Operation || this instanceof BlackOperation) { + competence *= inst.skillMultipliers.successChanceOperation; + } + if (this instanceof Contract) { + competence *= inst.skillMultipliers.successChanceContract; + } + if (this.isStealth) { + competence *= inst.skillMultipliers.successChanceStealth; + } + if (this.isKill) { + competence *= inst.skillMultipliers.successChanceKill; + } + + //Augmentation multiplier + competence *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_success_chance_mult; + + if (isNaN(competence)) {throw new Error("Competence calculated as NaN in Action.getSuccessChance()");} + return Math.min(1, competence / difficulty); +} + +//Tests for success. Should be called when an action has completed +// @inst - Bladeburner Object +Action.prototype.attempt = function(inst) { + return (Math.random() < this.getSuccessChance(inst)); +} + +Action.prototype.getActionTime = function(inst) { + var difficulty = this.getDifficulty(); + var baseTime = difficulty / DifficultyToTimeFactor; + var skillFac = inst.skillMultipliers.actionTime; //Always < 1 + + var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * inst.skillMultipliers.effAgi; + var effDexterity = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity * inst.skillMultipliers.effDex; + var statFac = 0.5 * (Math.pow(effAgility, 0.03) + Math.pow(effDexterity, 0.03)); //Always > 1 + + baseTime = Math.max(1, baseTime * skillFac / statFac); + + if (this instanceof Contract) { + return Math.ceil(baseTime); + } else if (this instanceof Operation) { + return Math.ceil(baseTime); + } else if (this instanceof BlackOperation) { + return Math.ceil(baseTime * 1.5); + } else { + throw new Error("Unrecognized Action Type in Action.getActionTime(this). Must be either Contract, Operation, or BlackOperation"); + } +} + +Action.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Action", this); +} +Action.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Action, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Action = Action; +var GeneralActions = {}; //Training, Field Analysis, Recruitment, etc. + +//Action Identifier +var ActionTypes = Object.freeze({ + "Idle": 1, + "Contract": 2, + "Operation": 3, + "BlackOp": 4, + "BlackOperation": 4, + "Training": 5, + "Recruitment": 6, + "FieldAnalysis": 7, + "Field Analysis": 7 +}); +function ActionIdentifier(params={}) { + if (params.name) {this.name = params.name;} + if (params.type) {this.type = params.type;} +} +ActionIdentifier.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("ActionIdentifier", this); +} +ActionIdentifier.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(ActionIdentifier, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.ActionIdentifier = ActionIdentifier; + +//Contracts +function Contract(params={}) { + Action.call(this, params); +} +Contract.prototype = Object.create(Action.prototype); +Contract.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Contract", this); +} +Contract.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Contract, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Contract = Contract; + +//Operations +function Operation(params={}) { + Action.call(this, params); + this.reqdRank = params.reqdRank ? params.reqdRank : 100; + this.teamCount = params.teamCount ? params.teamCount : 0; //# of team members to use +} +Operation.prototype = Object.create(Action.prototype); +Operation.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Operation", this); +} +Operation.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Operation, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Operation = Operation; + +//Black Operations +function BlackOperation(params={}) { + Operation.call(this, params); + + //Black ops are one time missions + this.count = 1; + this.countGrowth = 0; +} +BlackOperation.prototype = Object.create(Action.prototype); +BlackOperation.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("BlackOperation", this); +} +BlackOperation.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(BlackOperation, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.BlackOperation = BlackOperation; +var BlackOperations = {}; + +function Bladeburner(params={}) { + this.numHosp = 0; //Number of hospitalizations + this.moneyLost = 0; //Money lost due to hospitalizations + this.rank = 0; + this.maxRank = 0; //Used to determine skill points + + this.skillPoints = 0; + this.totalSkillPoints = 0; + + this.teamSize = 0; //Number of team members + this.teamLost = 0; //Number of team members lost + + this.storedCycles = 0; + + this.randomEventCounter = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 600); //5-10 minutes + + //These times are in seconds + this.actionTimeToComplete = 0; //0 or -1 is an infinite running action (like training) + this.actionTimeCurrent = 0; + + //ActionIdentifier Object + var idleActionType = ActionTypes["Idle"]; + this.action = new ActionIdentifier({type:idleActionType}); + + this.cities = {}; + for (var i = 0; i < CityNames.length; ++i) { + this.cities[CityNames[i]] = new City({name:CityNames[i]}); + } + this.city = _Location_js__WEBPACK_IMPORTED_MODULE_3__["Locations"].Sector12; + + //Map of SkillNames -> level + this.skills = {}; + this.skillMultipliers = {}; + this.updateSkillMultipliers(); //Calls resetSkillMultipliers() + + //Max Stamina is based on stats and Bladeburner-specific bonuses + this.staminaBonus = 0; //Gained from training + this.maxStamina = 0; + this.calculateMaxStamina(); + this.stamina = this.maxStamina; + + //Contracts and Operations objects. These objects have unique + //properties because they are randomized in each instance and have stats like + //successes/failures, so they need to be saved/loaded by the game. + this.contracts = {}; + this.operations = {}; + + //Object that contains name of all Black Operations that have been completed + this.blackops = {}; + + //Flags for whether these actions should be logged to console + this.logging = { + general:true, + contracts:true, + ops:true, + blackops:true, + events:true, + } + + //Simple automation values + this.automateEnabled = false; + this.automateActionHigh = 0; + this.automateThreshHigh = 0; //Stamina Threshold + this.automateActionLow = 0; + this.automateThreshLow = 0; //Stamina Threshold + + //Initialization + initBladeburner(); + this.initializeDomElementRefs(); + if (params.new) {this.create();} +} + +Bladeburner.prototype.create = function() { + this.contracts["Tracking"] = new Contract({ + name:"Tracking", + desc:"Identify and locate Synthoids. This contract involves reconnaissance " + + "and information-gathering ONLY. Do NOT engage. Stealth is of the utmost importance.

" + + "Successfully completing Tracking contracts will slightly improve your Synthoid population estimate for " + + "whatever city you are currently in.", + baseDifficulty:125,difficultyFac:1.02,rewardFac:1.041, + rankGain:0.3, hpLoss:0.5, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 800), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5), + weights:{hack:0,str:0.05,def:0.05,dex:0.35,agi:0.35,cha:0.1, int:0.05}, + decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.9, int:1}, + isStealth:true + }); + this.contracts["Bounty Hunter"] = new Contract({ + name:"Bounty Hunter", + desc:"Hunt down and capture fugitive Synthoids. These Synthoids are wanted alive.

" + + "Successfully completing a Bounty Hunter contract will lower the population in your " + + "current city, and will also increase its chaos level.", + baseDifficulty:250, difficultyFac:1.04,rewardFac:1.085, + rankGain:0.9, hpLoss:1, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(200, 750), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 3), + weights:{hack:0,str:0.15,def:0.15,dex:0.25,agi:0.25,cha:0.1, int:0.1}, + decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9}, + isKill:true + }); + this.contracts["Retirement"] = new Contract({ + name:"Retirement", + desc:"Hunt down and retire (kill) rogue Synthoids.

" + + "Successfully copmleting a Retirement contract will lower the population in your current " + + "city, and will also increase its chaos level.", + baseDifficulty:200, difficultyFac:1.03, rewardFac:1.065, + rankGain:0.6, hpLoss:1, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 900), countGrowth:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1,4), + weights:{hack:0,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0.1, int:0.1}, + decays:{hack:0,str:0.91,def:0.91,dex:0.91,agi:0.91,cha:0.8, int:0.9}, + isKill:true + }); + + this.operations["Investigation"] = new Operation({ + name:"Investigation", + desc:"As a field agent, investigate and identify Synthoid " + + "populations, movements, and operations.

Successful " + + "Investigation ops will increase the accuracy of your " + + "synthoid data.

" + + "You will NOT lose HP from failed Investigation ops.", + baseDifficulty:400, difficultyFac:1.03,rewardFac:1.07,reqdRank:25, + rankGain:2, rankLoss:0.2, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(50, 400), countGrowth:1, + weights:{hack:0.25,str:0.05,def:0.05,dex:0.2,agi:0.1,cha:0.25, int:0.1}, + decays:{hack:0.85,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9}, + isStealth:true + }); + this.operations["Undercover Operation"] = new Operation({ + name:"Undercover Operation", + desc:"Conduct undercover operations to identify hidden " + + "and underground Synthoid communities and organizations.

" + + "Successful Undercover ops will increase the accuracy of your synthoid " + + "data.", + baseDifficulty:500, difficultyFac:1.04, rewardFac:1.09, reqdRank:100, + rankGain:4, rankLoss:0.4, hpLoss:2, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(50, 300), countGrowth:1, + weights:{hack:0.2,str:0.05,def:0.05,dex:0.2,agi:0.2,cha:0.2, int:0.1}, + decays:{hack:0.8,str:0.9,def:0.9,dex:0.9,agi:0.9,cha:0.7, int:0.9}, + isStealth:true + }); + this.operations["Sting Operation"] = new Operation({ + name:"Sting Operation", + desc:"Conduct a sting operation to bait and capture particularly " + + "notorious Synthoid criminals.", + baseDifficulty:650, difficultyFac:1.04, rewardFac:1.095, reqdRank:500, + rankGain:5, rankLoss:0.5, hpLoss:2.5, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25,400), countGrowth:0.75, + weights:{hack:0.25,str:0.05,def:0.05,dex:0.25,agi:0.1,cha:0.2, int:0.1}, + decays:{hack:0.8,str:0.85,def:0.85,dex:0.85,agi:0.85,cha:0.7, int:0.9}, + isStealth:true + }); + this.operations["Raid"] = new Operation({ + name:"Raid", + desc:"Lead an assault on a known Synthoid community. Note that " + + "there must be an existing Synthoid community in your current city " + + "in order for this Operation to be successful", + baseDifficulty:800, difficultyFac:1.045, rewardFac:1.1, reqdRank:3000, + rankGain:50,rankLoss:2.5,hpLoss:50, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 150), countGrowth:0.2, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, + isKill:true + }); + this.operations["Stealth Retirement Operation"] = new Operation({ + name:"Stealth Retirement Operation", + desc:"Lead a covert operation to retire Synthoids. The " + + "objective is to complete the task without " + + "drawing any attention. Stealth and discretion are key.", + baseDifficulty:1000, difficultyFac:1.05, rewardFac:1.11, reqdRank:20e3, + rankGain:20, rankLoss:2, hpLoss:10, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 250), countGrowth:0.1, + weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, + decays:{hack:0.7,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.9}, + isStealth:true, isKill:true + }); + this.operations["Assassination"] = new Operation({ + name:"Assassination", + desc:"Assassinate Synthoids that have been identified as " + + "important, high-profile social and political leaders " + + "in the Synthoid communities.", + baseDifficulty:1500, difficultyFac:1.06, rewardFac:1.14, reqdRank:50e3, + rankGain:40, rankLoss:4, hpLoss:5, + count:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(25, 200), countGrowth:0.1, + weights:{hack:0.1,str:0.1,def:0.1,dex:0.3,agi:0.3,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.8}, + isStealth:true, isKill:true + }); +} + +Bladeburner.prototype.storeCycles = function(numCycles=1) { + this.storedCycles += numCycles; +} + +Bladeburner.prototype.process = function() { + //If the Player starts doing some other actions, set action to idle and alert + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].isWorking) { + if (this.action.type !== ActionTypes["Idle"]) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Your Bladeburner action was cancelled because you started " + + "doing something else"); + } + this.resetAction(); + } + + //A 'tick' for this mechanic is one second (= 5 game cycles) + if (this.storedCycles >= CyclesPerSecond) { + var seconds = Math.floor(this.storedCycles / CyclesPerSecond); + seconds = Math.min(seconds, 5); //Max of 5 'ticks' + this.storedCycles -= seconds * CyclesPerSecond; + + //Stamina + this.calculateMaxStamina(); + this.stamina += (this.calculateStaminaGainPerSecond() * seconds); + this.stamina = Math.min(this.maxStamina, this.stamina); + + //Count increase for contracts/operations + for (var contractName in this.contracts) { + if (this.contracts.hasOwnProperty(contractName)) { + var contract = this.contracts[contractName]; + contract.count += (seconds * contract.countGrowth/ActionCountGrowthPeriod); + } + } + for (var operationName in this.operations) { + if (this.operations.hasOwnProperty(operationName)) { + var op = this.operations[operationName]; + op.count += (seconds * op.countGrowth/ActionCountGrowthPeriod); + } + } + + //Chaos goes down very slowly + for (var i = 0; i < CityNames.length; ++i) { + var city = this.cities[CityNames[i]]; + if (!(city instanceof City)) {throw new Error("Invalid City object when processing passive chaos reduction in Bladeburner.process");} + city.chaos -= (0.0001 * seconds); + city.chaos = Math.max(0, city.chaos); + } + + //Random Events + this.randomEventCounter -= seconds; + if (this.randomEventCounter <= 0) { + this.randomEvent(); + this.randomEventCounter = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(300, 600); + } + + this.processAction(seconds); + + //Automation + if (this.automateEnabled) { + if (this.stamina <= this.automateThreshLow) { + if (this.action.name !== this.automateActionLow.name || this.action.type !== this.automateActionLow.type) { + this.action = this.automateActionLow; + this.startAction(this.action); + } + } else if (this.stamina >= this.automateThreshHigh) { + if (this.action.name !== this.automateActionHigh.name || this.action.type !== this.automateActionHigh.type) { + this.action = this.automateActionHigh; + this.startAction(this.action); + } + } + } + + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { + this.updateContent(); + } + } +} + +Bladeburner.prototype.calculateMaxStamina = function() { + var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * this.skillMultipliers.effAgi; + var maxStamina = (Math.pow(effAgility, 0.8) + this.staminaBonus); + maxStamina *= this.skillMultipliers.stamina; + maxStamina *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_max_stamina_mult; + if (isNaN(maxStamina)) {throw new Error("Max Stamina calculated to be NaN in Bladeburner.calculateMaxStamina()");} + this.maxStamina = maxStamina; +} + +Bladeburner.prototype.calculateStaminaGainPerSecond = function() { + var effAgility = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility * this.skillMultipliers.effAgi; + var maxStaminaBonus = this.maxStamina / MaxStaminaToGainFactor; + var gain = (StaminaGainPerSecond + maxStaminaBonus) * Math.pow(effAgility, 0.17); + return gain * (this.skillMultipliers.stamina * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_stamina_gain_mult); +} + +Bladeburner.prototype.calculateStaminaPenalty = function() { + return Math.min(1, this.stamina / (0.5 * this.maxStamina)); +} + +Bladeburner.prototype.changeRank = function(change) { + if (isNaN(change)) {throw new Error("NaN passed into Bladeburner.changeRank()");} + this.rank += change; + if (this.rank < 0) {this.rank = 0;} + this.maxRank = Math.max(this.rank, this.maxRank); + + var bladeburnersFactionName = "Bladeburners"; + if (Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["factionExists"])(bladeburnersFactionName)) { + var bladeburnerFac = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][bladeburnersFactionName]; + if (!(bladeburnerFac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { + throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button"); + } + if (bladeburnerFac.isMember) { + bladeburnerFac.playerReputation += (RankToFactionRepFactor * change * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].faction_rep_mult); + } + } + + //Gain skill points. You get 1 every 4 ranks + var rankNeededForSp = (this.totalSkillPoints+1) * RanksPerSkillPoint; + if (this.maxRank >= rankNeededForSp) { + //Calculate how many skill points to gain + var gainedSkillPoints = Math.floor((this.maxRank - rankNeededForSp) / RanksPerSkillPoint + 1); + this.skillPoints += gainedSkillPoints; + this.totalSkillPoints += gainedSkillPoints; + } +} + +Bladeburner.prototype.getCurrentCity = function() { + var city = this.cities[this.city]; + if (!(city instanceof City)) { + throw new Error("Bladeburner.getCurrentCity() did not properly return a City object"); + } + return city; +} + +Bladeburner.prototype.resetSkillMultipliers = function() { + this.skillMultipliers = { + successChanceAll:1, + successChanceStealth:1, + successChanceKill:1, + successChanceContract:1, + successChanceOperation:1, + successChanceEstimate:1, + actionTime:1, + effHack:1, + effStr:1, + effDef:1, + effDex:1, + effAgi:1, + effCha:1, + effInt:1, + stamina:1, + weaponAbility:1, + gunAbility:1, + }; +} + +Bladeburner.prototype.updateSkillMultipliers = function() { + this.resetSkillMultipliers(); + for (var skillName in this.skills) { + if (this.skills.hasOwnProperty(skillName)) { + var skill = Skills[skillName]; + if (skill == null) { + throw new Error("Could not find Skill Object for: " + skillName); + } + var level = this.skills[skillName]; + if (level == null || level <= 0) {continue;} //Not upgraded + + var multiplierNames = Object.keys(this.skillMultipliers); + for (var i = 0; i < multiplierNames.length; ++i) { + var multiplierName = multiplierNames[i]; + if (skill[multiplierName] != null && !isNaN(skill[multiplierName])) { + var value = skill[multiplierName] * level; + var multiplierValue = 1 + (value / 100); + if (multiplierName === "actionTime") { + multiplierValue = 1 - (value / 100); + } + this.skillMultipliers[multiplierName] *= multiplierValue; + } + } + } + } +} + +Bladeburner.prototype.upgradeSkill = function(skill) { + //This does NOT handle deduction of skill points + var skillName = skill.name; + if (this.skills[skillName]) { + ++this.skills[skillName]; + } else { + this.skills[skillName] = 1; + } + if (isNaN(this.skills[skillName]) || this.skills[skillName] < 0) { + throw new Error("Level of Skill " + skillName + " is invalid: " + this.skills[skillName]); + } + this.updateSkillMultipliers(); +} + +Bladeburner.prototype.getActionObject = function(actionId) { + //Given an ActionIdentifier object, returns the corresponding + //Contract, Operation, or BlackOperation object + switch (actionId.type) { + case ActionTypes["Contract"]: + return this.contracts[actionId.name]; + break; + case ActionTypes["Operation"]: + return this.operations[actionId.name]; + break; + case ActionTypes["BlackOp"]: + case ActionTypes["BlackOperation"]: + return BlackOperations[actionId.name]; + break; + default: + return null; + console.log("WARNING: Bladeburner.getActionObject() called with an unexpected " + + "ActionIdentifier type: " + actionId.type); + } +} + +//Sets the player to the "IDLE" action +Bladeburner.prototype.resetAction = function() { + this.action = new ActionIdentifier({type:ActionTypes.Idle}); +} + +Bladeburner.prototype.startAction = function(actionId) { + this.action = actionId; + this.actionTimeCurrent = 0; + switch (actionId.type) { + case ActionTypes["Idle"]: + this.actionTimeToComplete = 0; + break; + case ActionTypes["Contract"]: + try { + var action = this.getActionObject(actionId); + if (action == null) { + throw new Error("Failed to get Contract Object for: " + actionId.name); + } + if (action.count < 1) {return this.resetAction();} + this.actionTimeToComplete = action.getActionTime(this); + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } + break; + case ActionTypes["Operation"]: + try { + var action = this.getActionObject(actionId); + if (action == null) { + throw new Error ("Failed to get Operation Object for: " + actionId.name); + } + if (action.count < 1) {return this.resetAction();} + this.actionTimeToComplete = action.getActionTime(this); + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } + break; + case ActionTypes["BlackOp"]: + case ActionTypes["BlackOperation"]: + try { + var action = this.getActionObject(actionId); + if (action == null) { + throw new Error("Failed to get BlackOperation object for: " + actionId.name); + } + this.actionTimeToComplete = action.getActionTime(this); + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } + break; + case ActionTypes["Training"]: + this.actionTimeToComplete = 30; + break; + case ActionTypes["Recruitment"]: + var effCharisma = _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma * this.skillMultipliers.effCha; + var charismaFactor = Math.pow(effCharisma, 0.81) + effCharisma / 90; + var time = Math.max(10, Math.round(BaseRecruitmentTimeNeeded - charismaFactor)); + this.actionTimeToComplete = time; + break; + case ActionTypes["FieldAnalysis"]: + case ActionTypes["Field Analysis"]: + this.actionTimeToComplete = 30; + break; + default: + throw new Error("Invalid Action Type in Bladeburner.startAction(): " + actionId.type); + break; + } +} + +Bladeburner.prototype.processAction = function(seconds) { + if (this.action.type === ActionTypes["Idle"]) {return;} + if (this.actionTimeToComplete <= 0) { + console.log("action.type: " + this.action.type); + throw new Error("Invalid actionTimeToComplete value: " + this.actionTimeToComplete); + } + if (!(this.action instanceof ActionIdentifier)) { + throw new Error("Bladeburner.action is not an ActionIdentifier Object"); + } + + this.actionTimeCurrent += seconds; + if (this.actionTimeCurrent >= this.actionTimeToComplete) { + return this.completeAction(); + } +} + +Bladeburner.prototype.completeAction = function() { + switch (this.action.type) { + case ActionTypes["Contract"]: + case ActionTypes["Operation"]: + try { + var isOperation = (this.action.type === ActionTypes["Operation"]); + var action = this.getActionObject(this.action); + if (action == null) { + throw new Error("Failed to get Contract/Operation Object for: " + this.action.name); + } + var difficulty = action.getDifficulty(); + var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor; + var rewardMultiplier = Math.pow(action.rewardFac, action.level-1); + + //Stamina loss is based on difficulty + this.stamina -= (BaseStaminaLoss * difficultyMultiplier); + if (this.stamina < 0) {this.stamina = 0;} + + //Process Contract/Operation success/failure + if (action.attempt(this)) { + this.gainActionStats(action, true); + ++action.successes; + --action.count; + + //Earn money for contracts + var moneyGain = 0; + if (!isOperation) { + moneyGain = ContractBaseMoneyGain * rewardMultiplier; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainMoney(moneyGain); + } + + if (isOperation) { + action.maxLevel = Math.floor(action.successes / OperationSuccessesPerLevel) + 1; + } else { + action.maxLevel = Math.floor(action.successes / ContractSuccessesPerLevel) + 1; + } + if (action.rankGain) { + var gain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankGain * rewardMultiplier, 10); + this.changeRank(gain); + if (isOperation && this.logging.ops) { + this.log(action.name + " successfully completed! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(gain, 3) + " rank"); + } else if (!isOperation && this.logging.contracts) { + this.log(action.name + " contract successfully completed! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(gain, 3) + " rank and " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(moneyGain).format("$0.000a")); + } + } + isOperation ? this.completeOperation(true) : this.completeContract(true); + } else { + this.gainActionStats(action, false); + ++action.failures; + var loss = 0, damage = 0; + if (action.rankLoss) { + loss = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankLoss * rewardMultiplier, 10); + this.changeRank(-1 * loss); + } + if (action.hpLoss) { + damage = action.hpLoss * difficultyMultiplier; + damage = Math.ceil(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(damage, 10)); + this.hpLost += damage; + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].takeDamage(damage)) { + ++this.numHosp; + this.moneyLost += (_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HospitalCostPerHp * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].max_hp); + } + } + var logLossText = ""; + if (loss > 0) {logLossText += "Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(loss, 3) + " rank.";} + if (damage > 0) {logLossText += "Took " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(damage, 0) + " damage.";} + if (isOperation && this.logging.ops) { + this.log(action.name + " failed! " + logLossText); + } else if (!isOperation && this.logging.contracts) { + this.log(action.name + " contract failed! " + logLossText); + } + isOperation ? this.completeOperation(false) : this.completeContract(false); + } + if (action.autoLevel) {action.level = action.maxLevel;} //Autolevel + this.startAction(this.action); //Repeat action + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } + break; + case ActionTypes["BlackOp"]: + case ActionTypes["BlackOperation"]: + try { + var action = this.getActionObject(this.action); + if (action == null || !(action instanceof BlackOperation)) { + throw new Error("Failed to get BlackOperation Object for: " + this.action.name); + } + var difficulty = action.getDifficulty(); + var difficultyMultiplier = Math.pow(difficulty, DiffMultExponentialFactor) + difficulty / DiffMultLinearFactor; + + //Stamina loss is based on difficulty + this.stamina -= (BaseStaminaLoss * difficultyMultiplier); + if (this.stamina < 0) {this.stamina = 0;} + + //Team loss variables + var teamCount = action.teamCount, teamLossMax; + + if (action.attempt(this)) { + this.gainActionStats(action, true); + action.count = 0; + this.blackops[action.name] = true; + var rankGain = 0; + if (action.rankGain) { + rankGain = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankGain, 10); + this.changeRank(rankGain); + } + teamLossMax = Math.ceil(teamCount/2); + + //Operation Daedalus + if (action.name === "Operation Daedalus") { + this.resetAction(); + return Object(_RedPill_js__WEBPACK_IMPORTED_MODULE_5__["hackWorldDaemon"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bitNodeN); + } + + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) { + this.createActionAndSkillsContent(); + } + + if (this.logging.blackops) { + this.log(action.name + " successful! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(rankGain, 1) + " rank"); + } + } else { + this.gainActionStats(action, false); + var rankLoss = 0, damage = 0; + if (action.rankLoss) { + rankLoss = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(action.rankLoss, 10); + this.changeRank(-1 * rankLoss); + } + if (action.hpLoss) { + damage = action.hpLoss * difficultyMultiplier; + damage = Math.ceil(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["addOffset"])(damage, 10)); + if (_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].takeDamage(damage)) { + ++this.numHosp; + this.moneyLost += (_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].HospitalCostPerHp * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].max_hp); + } + } + teamLossMax = Math.floor(teamCount); + + if (this.logging.blackops) { + this.log(action.name + " failed! Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(rankLoss, 1) + " rank and took" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(damage, 0) + " damage"); + } + } + + this.resetAction(); //Stop regardless of success or fail + + //Calculate team lossses + if (teamCount >= 1) { + var losses = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, teamLossMax); + this.teamSize -= losses; + this.teamLost += losses; + if (this.logging.blackops) { + this.log("You lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(losses, 0) + " team members during " + action.name); + } + } + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } + break; + case ActionTypes["Training"]: + this.stamina -= (0.5 * BaseStaminaLoss); + var strExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult, + defExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult, + dexExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult, + agiExpGain = 30 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult, + staminaGain = 0.04 * this.skillMultipliers.stamina; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainStrengthExp(strExpGain); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDefenseExp(defExpGain); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDexterityExp(dexExpGain); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainAgilityExp(agiExpGain); + this.staminaBonus += (staminaGain); + if (this.logging.general) { + this.log("Training completed. Gained: " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(strExpGain, 1) + " str exp, " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(defExpGain, 1) + " def exp, " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(dexExpGain, 1) + " dex exp, " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(agiExpGain, 1) + " agi exp, " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(staminaGain, 3) + " max stamina"); + } + this.startAction(this.action); //Repeat action + break; + case ActionTypes["FieldAnalysis"]: + case ActionTypes["Field Analysis"]: + //Does not use stamina. Effectiveness depends on hacking, int, and cha + var eff = 0.04 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_skill, 0.3) + + 0.04 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].intelligence, 0.9) + + 0.02 * Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma, 0.3); + eff *= _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_analysis_mult; + if (isNaN(eff) || eff < 0) { + throw new Error("Field Analysis Effectiveness calculated to be NaN or negative"); + } + var hackingExpGain = 20 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult, + charismaExpGain = 20 * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainHackingExp(hackingExpGain); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainIntelligenceExp(BaseIntGain); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(charismaExpGain); + this.changeRank(0.1); + console.log("DEBUG: Field Analysis effectiveness is " + (eff * this.skillMultipliers.successChanceEstimate)); + this.getCurrentCity().improvePopulationEstimateByPercentage(eff * this.skillMultipliers.successChanceEstimate); + if (this.logging.general) { + this.log("Field analysis completed. Gained 0.1 rank, " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(hackingExpGain, 1) + " hacking exp, and " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(charismaExpGain, 1) + " charisma exp"); + } + this.startAction(this.action); //Repeat action + break; + case ActionTypes["Recruitment"]: + var successChance = Math.pow(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma, 0.45) / (this.teamSize + 1); + console.log("Bladeburner recruitment success chance: " + successChance); + if (Math.random() < successChance) { + var expGain = 2 * BaseStatGain * this.actionTimeToComplete; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(expGain); + ++this.teamSize; + if (this.logging.general) { + this.log("Successfully recruited a team member! Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(expGain, 1) + " charisma exp"); + } + } else { + var expGain = BaseStatGain * this.actionTimeToComplete; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(expGain); + if (this.logging.general) { + this.log("Failed to recruit a team member. Gained " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(expGain, 1) + " charisma exp"); + } + } + this.startAction(this.action); //Repeat action + break; + default: + break; + } +} + +Bladeburner.prototype.completeContract = function(success) { + if (this.action.type !== ActionTypes.Contract) { + throw new Error("completeContract() called even though current action is not a Contract"); + } + var city = this.getCurrentCity(); + if (success) { + switch (this.action.name) { + case "Tracking": + //Increase estimate accuracy by a relatively small amount + city.improvePopulationEstimateByCount(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(100, 1e3)); + break; + case "Bounty Hunter": + city.changePopulationByCount(-1, {estChange:-1}); + city.changeChaosByCount(0.02); + break; + case "Retirement": + city.changePopulationByCount(-1, {estChange:-1}); + city.changeChaosByCount(0.04); + break; + default: + throw new Error("Invalid Action name in completeContract: " + this.action.name); + } + } +} + +Bladeburner.prototype.completeOperation = function(success) { + if (this.action.type !== ActionTypes.Operation) { + throw new Error("completeOperation() called even though current action is not an Operation"); + } + var action = this.getActionObject(this.action); + if (action == null) { + throw new Error("Failed to get Contract/Operation Object for: " + this.action.name); + } + + //Calculate team losses + var teamCount = action.teamCount, max; + if (teamCount >= 1) { + if (success) { + max = Math.ceil(teamCount/2); + } else { + max = Math.floor(teamCount) + } + var losses = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, max); + this.teamSize -= losses; + this.teamLost += losses; + if (this.logging.ops && losses > 0) { + this.log("Lost " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(losses, 0) + " team members during this " + action.name); + } + } + + var city = this.getCurrentCity(); + if (this.logging.ops) { + if (success) { + this.log(action.name + " completed successfully! ") + } else { + + } + } + switch (action.name) { + case "Investigation": + if (success) { + city.improvePopulationEstimateByPercentage(0.4 * this.skillMultipliers.successChanceEstimate); + if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) { + city.improveCommunityEstimate(1); + } + } else { + this.triggerPotentialMigration(this.city, 0.1); + } + break; + case "Undercover Operation": + if (success) { + city.improvePopulationEstimateByPercentage(0.8 * this.skillMultipliers.successChanceEstimate); + if (Math.random() < (0.02 * this.skillMultipliers.successChanceEstimate)) { + city.improveCommunityEstimate(1); + } + } else { + this.triggerPotentialMigration(this.city, 0.15); + } + break; + case "Sting Operation": + if (success) { + city.changePopulationByPercentage(-0.1, {changeEstEqually:true, nonZero:true}); + } + city.changeChaosByCount(0.1); + break; + case "Raid": + if (success) { + city.changePopulationByPercentage(-1, {changeEstEqually:true, nonZero:true}); + --city.comms; + --city.commsEst; + } else { + var change = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-3, -1); + city.changePopulationByPercentage(change, {nonZero:true}); + } + city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(1, 5)); + break; + case "Stealth Retirement Operation": + if (success) { + city.changePopulationByPercentage(-0.5, {changeEstEqually:true,nonZero:true}); + } + city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-3, -1)); + break; + case "Assassination": + if (success) { + city.changePopulationByCount(-1, {estChange:-1}); + } + city.changeChaosByPercentage(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(-5, 5)); + break; + default: + throw new Error("Invalid Action name in completeOperation: " + this.action.name); + } +} + +//Process stat gains from Contracts, Operations, and Black Operations +//@action(Action obj) - Derived action class +//@success(bool) - Whether action was successful +Bladeburner.prototype.gainActionStats = function(action, success) { + var difficulty = action.getDifficulty(); + + //Gain multiplier based on difficulty. If this changes then the + //same variable calculated in completeAction() needs to change too + var difficultyMult = Math.pow(difficulty, 0.21); + + var time = this.actionTimeToComplete; + var successMult = success ? 1 : 0.5; + + var unweightedGain = time * BaseStatGain * successMult * difficultyMult; + var unweightedIntGain = time * BaseIntGain * successMult * difficultyMult; + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainHackingExp(unweightedGain * action.weights.hack * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].hacking_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainStrengthExp(unweightedGain * action.weights.str * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].strength_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDefenseExp(unweightedGain * action.weights.def * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].defense_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainDexterityExp(unweightedGain * action.weights.dex * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].dexterity_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainAgilityExp(unweightedGain * action.weights.agi * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].agility_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainCharismaExp(unweightedGain * action.weights.cha * _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].charisma_exp_mult); + _Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].gainIntelligenceExp(unweightedIntGain * action.weights.int); +} + +Bladeburner.prototype.randomEvent = function() { + var chance = Math.random(); + + //Choose random source/destination city for events + var sourceCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; + var sourceCity = this.cities[sourceCityName]; + if (!(sourceCity instanceof City)) { + throw new Error("sourceCity was not a City object in Bladeburner.randomEvent()"); + } + + var destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; + while (destCityName === sourceCityName) { + destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; + } + var destCity = this.cities[destCityName]; + + if (!(sourceCity instanceof City) || !(destCity instanceof City)) { + throw new Error("sourceCity was not a City object in Bladeburner.randomEvent()"); + } + + if (chance <= 0.05) { + //New Synthoid Community, 5% + ++sourceCity.comms; + var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop += count; + if (this.logging.events) { + this.log("Intelligence indicates that a new Synthoid community was formed in a city"); + } + } else if (chance <= 0.1) { + //Synthoid Community Migration, 5% + if (sourceCity.comms <= 0) { + //If no comms in source city, then instead trigger a new Synthoid community event + ++sourceCity.comms; + var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop += count; + if (this.logging.events) { + this.log("Intelligence indicates that a new Synthoid community was formed in a city"); + } + } else { + --sourceCity.comms; + ++destCity.comms; + + //Change pop + var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(10, 20) / 100; + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop -= count; + destCity.pop += count; + + if (this.logging.events) { + this.log("Intelligence indicates that a Synthoid community migrated from " + sourceCityName + " to some other city"); + } + } + } else if (chance <= 0.3) { + //New Synthoids (non community), 20% + var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(8, 24) / 100; + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop += count; + if (this.logging.events) { + this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly"); + } + } else if (chance <= 0.5) { + //Synthoid migration (non community) 20% + this.triggerMigration(sourceCityName); + if (this.logging.events) { + this.log("Intelligence indicates that a large number of Synthoids migrated from " + sourceCityName + " to some other city"); + } + } else if (chance <= 0.7) { + //Synthoid Riots (+chaos), 20% + sourceCity.chaos += 1; + sourceCity.chaos *= (1 + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(5, 10) / 100); + if (this.logging.events) { + this.log("Tensions between Synthoids and humans lead to riots in " + sourceCityName + "! Chaos increased"); + } + } else if (chance <= 0.9) { + //Less Synthoids, 20% + var percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(5, 20) / 100; + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop -= count; + if (this.logging.events) { + this.log("Intelligence indicates that the Synthoid population of " + sourceCityName + " just changed significantly"); + } + } + //20% chance of nothing happening +} + +Bladeburner.prototype.triggerPotentialMigration = function(sourceCityName, chance) { + if (chance == null || isNaN(chance)) { + console.log("ERROR: Invalid 'chance' parameter passed into Bladeburner.triggerPotentialMigration()"); + } + if (chance > 1) {chance /= 100;} + if (Math.random() < chance) {this.triggerMigration(sourceCityName);} +} + +Bladeburner.prototype.triggerMigration = function(sourceCityName) { + var destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; + while (destCityName === sourceCityName) { + destCityName = CityNames[Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(0, 5)]; + } + var destCity = this.cities[destCityName]; + var sourceCity = this.cities[sourceCityName]; + if (destCity == null || sourceCity == null) { + throw new Error("Failed to find City with name: " + destCityName); + } + var rand = Math.random(), percentage = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(3, 15) / 100; + + if (rand < 0.05 && sourceCity.comms > 0) { //5% chance for community migration + percentage *= Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["getRandomInt"])(2, 4); //Migration increases population change + --sourceCity.comms; + ++destCity.comms; + } + var count = Math.round(sourceCity.pop * percentage); + sourceCity.pop -= count; + destCity.pop += count; +} + +var DomElems = {}; + +Bladeburner.prototype.initializeDomElementRefs = function() { + DomElems = { + bladeburnerDiv: null, + + //Main Divs + overviewConsoleParentDiv: null, + + overviewDiv: null, //Overview of stats that stays fixed on left + actionAndSkillsDiv: null, //Panel for different sections (contracts, ops, skills) + currentTab: null, //Contracts, Operations, Black Ops, Skills + + consoleDiv: null, + consoleTable: null, + consoleInputRow: null, //tr + consoleInputCell: null, //td + consoleInputHeader: null, //"> " + consoleInput: null, //Actual input element + + //Overview Content + overviewRank: null, + overviewStamina: null, + overviewStaminaHelpTip: null, + overviewGen1: null, //Stamina Penalty, Team, Hospitalized stats, current city + overviewEstPop: null, + overviewEstPopHelpTip: null, + overviewEstComms: null, + overviewChaos: null, + overviewSkillPoints: null, + overviewAugSuccessMult: null, + overviewAugMaxStaminaMult: null, + overviewAugStaminaGainMult: null, + overviewAugAnalysisMult: null, + + //Actions and Skills Content + actionsAndSkillsDesc: null, + actionsAndSkillsList: null, //ul element of all UI elements in this panel + generalActions: {}, + contracts: {}, + operations: {}, + blackops: {}, + skills: {}, + }; +} + +Bladeburner.prototype.createContent = function() { + DomElems.bladeburnerDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + id:"bladeburner-container", position:"fixed", class:"generic-menupage-container", + }); + + //Parent Div for Overview and Console + DomElems.overviewConsoleParentDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + height:"60%", display:"block", position:"relative", + }); + + //Overview and Action/Skill pane + DomElems.overviewDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + width:"30%", display:"inline-block", border:"1px solid white", + }); + + DomElems.actionAndSkillsDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + height:"60%", width:"70%", display:"block", + border:"1px solid white", margin:"6px", padding:"6px", + }); + + DomElems.currentTab = "general"; + + this.createOverviewContent(); + this.createActionAndSkillsContent(); + + //Console + DomElems.consoleDiv = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-console-div", + clickListener:()=>{ + if (DomElems.consoleInput instanceof Element) { + DomElems.consoleInput.focus(); + } + return false; + } + }); + DomElems.consoleTable = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("table", {class:"bladeburner-console-table"}); + DomElems.consoleInputRow = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("tr", {class:"bladeburner-console-input-row", id:"bladeubrner-console-input-row"}); + DomElems.consoleInputCell = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("td", {class:"bladeburner-console-input-cell"}); + DomElems.consoleInputHeader = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", {innerText:"> "}); + DomElems.consoleInput = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { + type:"text", class:"bladeburner-console-input", tabIndex:1, + onfocus:()=>{DomElems.consoleInput.value = DomElems.consoleInput.value} + }); + + DomElems.consoleInputCell.appendChild(DomElems.consoleInputHeader); + DomElems.consoleInputCell.appendChild(DomElems.consoleInput); + DomElems.consoleInputRow.appendChild(DomElems.consoleInputCell); + DomElems.consoleTable.appendChild(DomElems.consoleInputRow); + DomElems.consoleDiv.appendChild(DomElems.consoleTable); + + DomElems.overviewConsoleParentDiv.appendChild(DomElems.overviewDiv); + DomElems.overviewConsoleParentDiv.appendChild(DomElems.consoleDiv); + DomElems.bladeburnerDiv.appendChild(DomElems.overviewConsoleParentDiv); + DomElems.bladeburnerDiv.appendChild(DomElems.actionAndSkillsDiv); + + document.getElementById("entire-game-container").appendChild(DomElems.bladeburnerDiv); + + this.postToConsole("Bladeburner Console BETA"); + this.postToConsole("Type 'help' to see console commands"); + DomElems.consoleInput.focus(); +} + +Bladeburner.prototype.clearContent = function() { + if (DomElems.bladeburnerDiv instanceof Element) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.bladeburnerDiv); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElement"])(DomElems.bladeburnerDiv); + } + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems); + this.initializeDomElementRefs(); +} + +Bladeburner.prototype.createOverviewContent = function() { + if (DomElems.overviewDiv == null) { + throw new Error("Bladeburner.createOverviewContent() called with DomElems.overviewDiv = null"); + } + + DomElems.overviewRank = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"Rank: ", + display:"inline-block", + tooltip:"Your rank within the Bladeburner division", + }); + + DomElems.overviewStamina = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"inline-block", + }); + + DomElems.overviewStaminaHelpTip = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + innerText:"?", class:"help-tip", + clickListener:()=>{ + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Performing actions will use up your stamina.

" + + "Your max stamina is determined primarily by your agility stat.

" + + "Your stamina gain rate is determined by both your agility and your " + + "max stamina. Higher max stamina leads to a higher gain rate.

" + + "Once your " + + "stamina falls below 50% of its max value, it begins to negatively " + + "affect the success rate of your contracts/operations. This penalty " + + "is shown in the overview panel. If the penalty is 15%, then this means " + + "your success rate would be multipled by 85% (100 - 15).

" + + "Your max stamina and stamina gain rate can also be increased by " + + "training, or through skills and Augmentation upgrades."); + } + }); + + DomElems.overviewGen1 = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + }); + + DomElems.overviewEstPop = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"Est. Synthoid Population: ", + display:"inline-block", + tooltip:"This is your Bladeburner division's estimate of how many Synthoids exist " + + "in your current city." + }); + + DomElems.overviewEstPopHelpTip = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + innerText:"?", class:"help-tip", + clickListener:()=>{ + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("The success rate of your contracts/operations depends on " + + "the population of Synthoids in your current city. " + + "The success rate that is shown to you is only an estimate, " + + "and it is based on your Synthoid population estimate.

" + + "Therefore, it is important that this Synthoid population estimate " + + "is accurate so that you have a better idea of your " + + "success rate for contracts/operations. Certain " + + "actions will increase the accuracy of your population " + + "estimate.

" + + "The Synthoid populations of cities can change due to your " + + "actions or random events. If random events occur, they will " + + "be logged in the Bladeburner Console."); + } + }); + + DomElems.overviewEstComms = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"Est. Synthoid Communities: ", + display:"inline-block", + tooltip:"This is your Bladeburner divison's estimate of how many Synthoid " + + "communities exist in your current city.", + }); + + DomElems.overviewChaos = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"City Chaos: ", + display:"inline-block", + tooltip:"The city's chaos level due to tensions and conflicts between humans and Synthoids. " + + "Having too high of a chaos level can make contracts and operations harder." + }); + + DomElems.overviewSkillPoints = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); + + DomElems.overviewAugSuccessMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); + DomElems.overviewAugMaxStaminaMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); + DomElems.overviewAugStaminaGainMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); + DomElems.overviewAugAnalysisMult = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", {display:"block"}); + + + DomElems.overviewDiv.appendChild(DomElems.overviewRank); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); + DomElems.overviewDiv.appendChild(DomElems.overviewStamina); + DomElems.overviewDiv.appendChild(DomElems.overviewStaminaHelpTip); + DomElems.overviewDiv.appendChild(DomElems.overviewGen1); + DomElems.overviewDiv.appendChild(DomElems.overviewEstPop); + DomElems.overviewDiv.appendChild(DomElems.overviewEstPopHelpTip); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); + DomElems.overviewDiv.appendChild(DomElems.overviewEstComms); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); + DomElems.overviewDiv.appendChild(DomElems.overviewChaos); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 2); + DomElems.overviewDiv.appendChild(DomElems.overviewSkillPoints); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); + DomElems.overviewDiv.appendChild(DomElems.overviewAugSuccessMult); + DomElems.overviewDiv.appendChild(DomElems.overviewAugMaxStaminaMult); + DomElems.overviewDiv.appendChild(DomElems.overviewAugStaminaGainMult); + DomElems.overviewDiv.appendChild(DomElems.overviewAugAnalysisMult); + + //Travel to new city button + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(DomElems.overviewDiv, 1); + DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerHTML:"Travel", class:"a-link-button", display:"inline-block", + clickListener:()=>{ + var popupId = "bladeburner-travel-popup-cancel-btn"; + var popupArguments = []; + popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Cancel Button + innerText:"Cancel", class:"a-link-button", + clickListener:()=>{ + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); return false; + } + })) + popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { //Info Text + innerText:"Travel to a different city for your Bladeburner " + + "activities. This does not cost any money. The city you are " + + "in for your Bladeburner duties does not affect " + + "your location in the game otherwise", + })); + for (var i = 0; i < CityNames.length; ++i) { + (function(inst, i) { + popupArguments.push(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + //Reusing this css class...it adds a border and makes it + //so that background color changes when you hover + class:"cmpy-mgmt-find-employee-option", + innerText:CityNames[i], + clickListener:()=>{ + inst.city = CityNames[i]; + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); + inst.updateOverviewContent(); + return false; + } + })); + })(this, i); + } + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, popupArguments); + } + })); + + //Faction button + var bladeburnersFactionName = "Bladeburners"; + if (Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["factionExists"])(bladeburnersFactionName)) { + var bladeburnerFac = _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][bladeburnersFactionName]; + if (!(bladeburnerFac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_2__["Faction"])) { + throw new Error("Could not properly get Bladeburner Faction object in Bladeburner UI Overview Faction button"); + } + DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Faction", class:"a-link-button", display:"inline-block", + tooltip:"Apply to the Bladeburner Faction, or go to the faction page if you are already a member", + clickListener:()=>{ + if (bladeburnerFac.isMember) { + _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadFactionContent(); + Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["displayFactionContent"])(bladeburnersFactionName); + } else { + if (this.rank >= 25) { + Object(_Faction_js__WEBPACK_IMPORTED_MODULE_2__["joinFaction"])(bladeburnerFac); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Congratulations! You were accepted into the Bladeburners faction"); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.overviewDiv); + this.createOverviewContent(); + } else { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("You need a rank of 25 to join the Bladeburners Faction!") + } + } + return false; + } + })); + } + + DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); + DomElems.overviewDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); + + this.updateOverviewContent(); +} + +Bladeburner.prototype.createActionAndSkillsContent = function() { + if (DomElems.currentTab == null) {DomElems.currentTab = "general";} + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.actionAndSkillsDiv); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.generalActions); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.contracts); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.operations); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.blackops); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["clearObject"])(DomElems.skills); + + //Navigation buttons + var currTab = DomElems.currentTab.toLowerCase(); + var buttons = ["General", "Contracts", "Operations", "BlackOps", "Skills"]; + for (var i = 0; i < buttons.length; ++i) { + (function(buttons, i, inst, currTab) { + + DomElems.actionAndSkillsDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:buttons[i], + class:currTab === buttons[i].toLowerCase() ? "bladeburner-nav-button-inactive" : "bladeburner-nav-button", + clickListener:()=>{ + DomElems.currentTab = buttons[i].toLowerCase(); + inst.createActionAndSkillsContent(); + return false; + } + })); + }) (buttons, i, this, currTab); + } + + //General info/description for each action + DomElems.actionsAndSkillsDesc = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", margin:"4px", padding:"4px" + }); + + //List for actions/skills + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(DomElems.actionsAndSkillsList); + DomElems.actionsAndSkillsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("ul"); + + switch(currTab) { + case "general": + this.createGeneralActionsContent(); + break; + case "contracts": + this.createContractsContent(); + break; + case "operations": + this.createOperationsContent(); + break; + case "blackops": + this.createBlackOpsContent(); + break; + case "skills": + this.createSkillsContent(); + break; + default: + throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent"); + } + this.updateContent(); + + DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsDesc); + DomElems.actionAndSkillsDiv.appendChild(DomElems.actionsAndSkillsList); +} + +Bladeburner.prototype.createGeneralActionsContent = function() { + if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { + throw new Error("Bladeburner.createGeneralActionsContent called with either " + + "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); + } + + DomElems.actionsAndSkillsDesc.innerText = + "These are generic actions that will assist you in your Bladeburner " + + "duties. They will not affect your Bladeburner rank in any way." + + for (var actionName in GeneralActions) { + if (GeneralActions.hasOwnProperty(actionName)) { + DomElems.generalActions[actionName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-action", name:actionName + }); + DomElems.actionsAndSkillsList.appendChild(DomElems.generalActions[actionName]); + } + } +} + +Bladeburner.prototype.createContractsContent = function() { + if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { + throw new Error("Bladeburner.createContractsContent called with either " + + "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); + } + + DomElems.actionsAndSkillsDesc.innerHTML = + "Complete contracts in order to increase your Bitburner rank and earn money. " + + "Failing a contract will cause you to lose HP, which can lead to hospitalization.

" + + "You can unlock higher-level contracts by successfully completing them. " + + "Higher-level contracts are more difficult, but grant more rank, experience, and money."; + + for (var contractName in this.contracts) { + if (this.contracts.hasOwnProperty(contractName)) { + DomElems.contracts[contractName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-action", name:contractName + }); + DomElems.actionsAndSkillsList.appendChild(DomElems.contracts[contractName]); + } + } +} + +Bladeburner.prototype.createOperationsContent = function() { + if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { + throw new Error("Bladeburner.createOperationsContent called with either " + + "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); + } + + DomElems.actionsAndSkillsDesc.innerHTML = + "Carry out operations for the Bladeburner division. " + + "Failing an operation will reduce your Bladeburner rank. It will also " + + "cause you to lose HP, which can lead to hospitalization. In general, " + + "operations are harder and more punishing than contracts, " + + "but are also more rewarding.

" + + "Operations can affect the chaos level and Synthoid population of your " + + "current city. The exact effects vary between different Operations.

" + + "For operations, you can use a team. You must first recruit team members. " + + "Having a larger team will improves your chances of success.

" + + "You can unlock higher-level operations by successfully completing them. " + + "Higher-level operations are more difficult, but grant more rank and experience."; + + for (var operationName in this.operations) { + if (this.operations.hasOwnProperty(operationName)) { + DomElems.operations[operationName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-action", name:operationName + }); + DomElems.actionsAndSkillsList.appendChild(DomElems.operations[operationName]); + } + } +} + +Bladeburner.prototype.createBlackOpsContent = function() { + if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { + throw new Error("Bladeburner.createBlackOpsContent called with either " + + "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); + } + + DomElems.actionsAndSkillsDesc.innerHTML = + "Black Operations (Black Ops) are special, one-time covert operations. " + + "Each Black Op must be unlocked successively by completing " + + "the one before it.

" + + "Like normal operations, you may use a team for Black Ops. Failing " + + "a black op will incur heavy HP and rank losses."; + + //Put Black Operations in sequence of required rank + var blackops = []; + for (var blackopName in BlackOperations) { + if (BlackOperations.hasOwnProperty(blackopName)) { + blackops.push(BlackOperations[blackopName]); + } + } + blackops.sort(function(a, b) { + return (a.reqdRank - b.reqdRank); + }); + + for (var i = 0; i < blackops.length; ++i) { + DomElems.blackops[blackops[i].name] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-action", name:blackops[i].name + }); + DomElems.actionsAndSkillsList.appendChild(DomElems.blackops[blackops[i].name]); + if (this.blackops[[blackops[i].name]] == null) {break;} //Can't be found in completed blackops + } +} + +Bladeburner.prototype.createSkillsContent = function() { + if (DomElems.actionsAndSkillsList == null || DomElems.actionsAndSkillsDesc == null) { + throw new Error("Bladeburner.createSkillsContent called with either " + + "DomElems.actionsAndSkillsList or DomElems.actionsAndSkillsDesc = null"); + } + + //Display Current multipliers + DomElems.actionsAndSkillsDesc.innerHTML = + "You will gain one skill point every " + RanksPerSkillPoint + " ranks.

" + + "Note that when upgrading a skill, the benefit for that skill is additive. " + + "However, the effects of different skills with each other is multiplicative.

" + var multKeys = Object.keys(this.skillMultipliers); + for (var i = 0; i < multKeys.length; ++i) { + var mult = this.skillMultipliers[multKeys[i]]; + if (mult && mult !== 1) { + mult = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(mult, 3); + switch(multKeys[i]) { + case "successChanceAll": + DomElems.actionsAndSkillsDesc.innerHTML += "Total Success Chance: x" + mult + "
"; + break; + case "successChanceStealth": + DomElems.actionsAndSkillsDesc.innerHTML += "Stealth Success Chance: x" + mult + "
"; + break; + case "successChanceKill": + DomElems.actionsAndSkillsDesc.innerHTML += "Retirement Success Chance: x" + mult + "
"; + break; + case "successChanceContract": + DomElems.actionsAndSkillsDesc.innerHTML += "Contract Success Chance: x" + mult + "
"; + break; + case "successChanceOperation": + DomElems.actionsAndSkillsDesc.innerHTML += "Operation Success Chance: x" + mult + "
"; + break; + case "successChanceEstimate": + DomElems.actionsAndSkillsDesc.innerHTML += "Synthoid Data Estimate: x" + mult + "
"; + break; + case "actionTime": + DomElems.actionsAndSkillsDesc.innerHTML += "Action Time: x" + mult + "
"; + break; + case "effHack": + DomElems.actionsAndSkillsDesc.innerHTML += "Hacking Skill: x" + mult + "
"; + break; + case "effStr": + DomElems.actionsAndSkillsDesc.innerHTML += "Strength: x" + mult + "
"; + break; + case "effDef": + DomElems.actionsAndSkillsDesc.innerHTML += "Defense: x" + mult + "
"; + break; + case "effDex": + DomElems.actionsAndSkillsDesc.innerHTML += "Dexterity: x" + mult + "
"; + break; + case "effAgi": + DomElems.actionsAndSkillsDesc.innerHTML += "Agility: x" + mult + "
"; + break; + case "effCha": + DomElems.actionsAndSkillsDesc.innerHTML += "Charisma: x" + mult + "
"; + break; + case "effInt": + DomElems.actionsAndSkillsDesc.innerHTML += "Intelligence: x" + mult + "
"; + break; + case "stamina": + DomElems.actionsAndSkillsDesc.innerHTML += "Stamina: x" + mult + "
"; + break; + case "weaponAbility": + //DomElems.actionsAndSkillsDesc.innerHTML += + break; + case "gunAbility": + //DomElems.actionsAndSkillsDesc.innerHTML + break; + default: + console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]); + break; + } + } + } + + //Skill Points + DomElems.actionAndSkillsDiv.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerHTML:"
Skill Points: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skillPoints, 0) + "" + })); + + //UI Element for each skill + for (var skillName in Skills) { + if (Skills.hasOwnProperty(skillName)) { + DomElems.skills[skillName] = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("div", { + class:"bladeburner-action", name:skillName + }); + DomElems.actionsAndSkillsList.appendChild(DomElems.skills[skillName]); + } + } +} + +Bladeburner.prototype.updateContent = function() { + this.updateOverviewContent(); + this.updateActionAndSkillsContent(); +} + +Bladeburner.prototype.updateOverviewContent = function() { + if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.Bladeburner) {return;} + DomElems.overviewRank.childNodes[0].nodeValue = "Rank: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.rank, 2); + DomElems.overviewStamina.innerText = "Stamina: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.stamina, 3) + " / " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.maxStamina, 3); + DomElems.overviewGen1.innerHTML = + "Stamina Penalty: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])((1-this.calculateStaminaPenalty())*100, 1) + "%

" + + "Team Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.teamSize, 0) + "
" + + "Team Members Lost: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.teamLost, 0) + "

" + + "Num Times Hospitalized: " + this.numHosp + "
" + + "Money Lost From Hospitalizations: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(this.moneyLost).format("$0.000a") + "

" + + "Current City: " + this.city + "
"; + + DomElems.overviewEstPop.childNodes[0].nodeValue = "Est. Synthoid Population: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_10___default()(this.getCurrentCity().popEst).format("0.000a"); + DomElems.overviewEstComms.childNodes[0].nodeValue = "Est. Synthoid Communities: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.getCurrentCity().comms, 0); + DomElems.overviewChaos.childNodes[0].nodeValue = "City Chaos: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.getCurrentCity().chaos); + DomElems.overviewSkillPoints.innerText = "Skill Points: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skillPoints, 0); + DomElems.overviewAugSuccessMult.innerText = "Aug. Success Chance Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_success_chance_mult*100, 1) + "%"; + DomElems.overviewAugMaxStaminaMult.innerText = "Aug. Max Stamina Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_max_stamina_mult*100, 1) + "%"; + DomElems.overviewAugStaminaGainMult.innerText = "Aug. Stamina Gain Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_stamina_gain_mult*100, 1) + "%"; + DomElems.overviewAugAnalysisMult.innerText = "Aug. Field Analysis Mult: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_4__["Player"].bladeburner_analysis_mult*100, 1) + "%"; +} + +Bladeburner.prototype.updateActionAndSkillsContent = function() { + if (DomElems.currentTab == null) {DomElems.currentTab = "general";} + switch(DomElems.currentTab.toLowerCase()) { + case "general": + var actionElems = Object.keys(DomElems.generalActions); + for (var i = 0; i < actionElems.length; ++i) { + var actionElem = DomElems.generalActions[actionElems[i]]; + var name = actionElem.name; + var actionObj = GeneralActions[name]; + if (actionObj == null) { + throw new Error("Could not find Object " + name + " in Bladeburner.updateActionAndSkillsContent()"); + } + if (this.action.type === ActionTypes[name]) { + actionElem.classList.add(ActiveActionCssClass); + } else { + actionElem.classList.remove(ActiveActionCssClass); + } + this.updateGeneralActionsUIElement(actionElem, actionObj); + } + break; + case "contracts": + var contractElems = Object.keys(DomElems.contracts); + for (var i = 0; i < contractElems.length; ++i) { + var contractElem = DomElems.contracts[contractElems[i]]; + var name = contractElem.name; + if (this.action.type === ActionTypes["Contract"] && name === this.action.name) { + contractElem.classList.add(ActiveActionCssClass); + } else { + contractElem.classList.remove(ActiveActionCssClass); + } + var contract = this.contracts[name]; + if (contract == null) { + throw new Error("Could not find Contract " + name + " in Bladeburner.updateActionAndSkillsContent()"); + } + this.updateContractsUIElement(contractElem, contract); + } + break; + case "operations": + var operationElems = Object.keys(DomElems.operations); + for (var i = 0; i < operationElems.length; ++i) { + var operationElem = DomElems.operations[operationElems[i]]; + var name = operationElem.name; + if (this.action.type === ActionTypes["Operation"] && name === this.action.name) { + operationElem.classList.add(ActiveActionCssClass); + } else { + operationElem.classList.remove(ActiveActionCssClass); + } + var operation = this.operations[name]; + if (operation == null) { + throw new Error("Could not find Operation " + name + " in Bladeburner.updateActionAndSkillsContent()"); + } + this.updateOperationsUIElement(operationElem, operation); + } + break; + case "blackops": + var blackopsElems = Object.keys(DomElems.blackops); + for (var i = 0; i < blackopsElems.length; ++i) { + var blackopElem = DomElems.blackops[blackopsElems[i]]; + var name = blackopElem.name; + if (this.action.type === ActionTypes["BlackOperation"] && name === this.action.name) { + blackopElem.classList.add(ActiveActionCssClass); + } else { + blackopElem.classList.remove(ActiveActionCssClass); + } + var blackop = BlackOperations[name]; + if (blackop == null) { + throw new Error("Could not find BlackOperation " + name + " in Bladeburner.updateActionAndSkillsContent()"); + } + this.updateBlackOpsUIElement(blackopElem, blackop); + } + break; + case "skills": + var skillElems = Object.keys(DomElems.skills); + for (var i = 0; i < skillElems.length; ++i) { + var skillElem = DomElems.skills[skillElems[i]]; + var name = skillElem.name; + var skill = Skills[name]; + if (skill == null) { + throw new Error("Could not find Skill " + name + " in Bladeburner.updateActionAndSkillsContent()"); + } + this.updateSkillsUIElement(skillElem, skill); + } + break; + default: + throw new Error("Invalid value for DomElems.currentTab in Bladeburner.createActionAndSkillsContent"); + } +} + +Bladeburner.prototype.updateGeneralActionsUIElement = function(el, action) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); + var isActive = el.classList.contains(ActiveActionCssClass); + + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header + innerText:isActive ? action.name + " (IN PROGRESS - " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" + : action.name, + display:"inline-block", + })); + + if (isActive) { //Progress bar if its active + var progress = this.actionTimeCurrent / this.actionTimeToComplete; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) + })); + } else { + //Start button + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Start", class: "a-link-button", + margin:"3px", padding:"3px", + clickListener:()=>{ + this.action.type = ActionTypes[action.name]; + this.action.name = action.name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + return false; + } + })); + } + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { //Info + innerHTML:action.desc, display:"inline-block" + })); + + +} + +Bladeburner.prototype.updateContractsUIElement = function(el, action) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); + var isActive = el.classList.contains(ActiveActionCssClass); + var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); + + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header + innerText:isActive ? action.name + " (IN PROGRESS - " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" + : action.name, + display:"inline-block" + })); + + if (isActive) { //Progress bar if its active + var progress = this.actionTimeCurrent / this.actionTimeToComplete; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) + })); + } else { //Start button + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Start", class: "a-link-button", + padding:"3px", margin:"3px", + clickListener:()=>{ + this.action.type = ActionTypes.Contract; + this.action.name = action.name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + return false; + } + })); + } + + //Level and buttons to change level + var maxLevel = (action.level >= action.maxLevel); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { + display:"inline-block", + innerText:"Level: " + action.level + " / " + action.maxLevel + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", + padding:"2px", margin:"2px", + tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", + display:"inline", + clickListener:()=>{ + ++action.level; + if (isActive) {this.startAction(this.action);} //Restart Action + this.updateContractsUIElement(el, action); + return false; + } + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", + padding:"2px", margin:"2px", + tooltip: isActive ? "WARNING: changing the level will restart the contract" : "", + display:"inline", + clickListener:()=>{ + --action.level; + if (isActive) {this.startAction(this.action);} //Restart Action + this.updateContractsUIElement(el, action); + return false; + } + })); + + var actionTime = action.getActionTime(this); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { //Info + display:"inline-block", + innerHTML:action.desc + "\n\n" + + "Estimated success chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + + "Time Required (s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 0) + "\n" + + "Contracts remaining: " + Math.floor(action.count) + "\n" + + "Successes: " + action.successes + "\n" + + "Failures: " + action.failures, + })); + + //Autolevel Checkbox + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); + var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("label", { + for:autolevelCheckboxId, innerText:"Autolevel",color:"white", + tooltip:"Automatically increase contract level when possible" + })); + var autolevelCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { + type:"checkbox", id:autolevelCheckboxId, margin:"4px", + checked:action.autoLevel, + changeListener:()=>{ + action.autoLevel = autolevelCheckbox.checked; + } + }); + el.appendChild(autolevelCheckbox); +} + +Bladeburner.prototype.updateOperationsUIElement = function(el, action) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); + var isActive = el.classList.contains(ActiveActionCssClass); + var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header + innerText:isActive ? action.name + " (IN PROGRESS - " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" + : action.name, + display:"inline-block" + })); + + if (isActive) { //Progress bar if its active + var progress = this.actionTimeCurrent / this.actionTimeToComplete; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) + })); + } else { //Start button and set Team Size button + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Start", class: "a-link-button", + margin:"3px", padding:"3px", + clickListener:()=>{ + this.action.type = ActionTypes.Operation; + this.action.name = action.name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + return false; + } + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", + margin:"3px", padding:"3px", + clickListener:()=>{ + var popupId = "bladeburner-operation-set-team-size-popup"; + var txt = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"Enter the amount of team members you would like to take on these " + + "operations. If you do not have the specified number of team members, " + + "then as many as possible will be used. Note that team members may " + + "be lost during operations." + + }); + var input = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { + type:"number", placeholder: "Team Members" + }); + var setBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Confirm", class:"a-link-button", + clickListener:()=>{ + var num = Math.round(parseFloat(input.value)); + if (isNaN(num)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") + } else { + action.teamCount = num; + this.updateOperationsUIElement(el, action); + } + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); + return false; + } + }); + var cancelBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Cancel", class:"a-link-button", + clickListener:()=>{ + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); + return false; + } + }); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); + } + })); + } + + //Level and buttons to change level + var maxLevel = (action.level >= action.maxLevel); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { + display:"inline-block", + innerText:"Level: " + action.level + " / " + action.maxLevel + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + class: maxLevel ? "a-link-button-inactive" : "a-link-button", innerHTML:"↑", + padding:"2px", margin:"2px", + tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", + display:"inline", + clickListener:()=>{ + ++action.level; + if (isActive) {this.startAction(this.action);} //Restart Action + this.updateOperationsUIElement(el, action); + return false; + } + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + class: (action.level <= 1) ? "a-link-button-inactive" : "a-link-button", innerHTML:"↓", + padding:"2px", margin:"2px", + tooltip: isActive ? "WARNING: changing the level will restart the Operation" : "", + display:"inline", + clickListener:()=>{ + --action.level; + if (isActive) {this.startAction(this.action);} //Restart Action + this.updateOperationsUIElement(el, action); + return false; + } + })); + + //General Info + var difficulty = action.getDifficulty(); + var actionTime = action.getActionTime(this); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("pre", { + display:"inline-block", + innerHTML:action.desc + "\n\n" + + "Estimated success chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + + "Time Required(s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 1) + "\n" + + "Operations remaining: " + Math.floor(action.count) + "\n" + + "Successes: " + action.successes + "\n" + + "Failures: " + action.failures, + })); + + //Autolevel Checkbox + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("br")); + var autolevelCheckboxId = "bladeburner-" + action.name + "-autolevel-checkbox"; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("label", { + for:autolevelCheckboxId, innerText:"Autolevel",color:"white", + tooltip:"Automatically increase operation level when possible" + })); + var autolevelCheckbox = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { + type:"checkbox", id:autolevelCheckboxId, margin:"4px", + checked:action.autoLevel, + changeListener:()=>{ + action.autoLevel = autolevelCheckbox.checked; + } + }); + el.appendChild(autolevelCheckbox); +} + +Bladeburner.prototype.updateBlackOpsUIElement = function(el, action) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); + var isActive = el.classList.contains(ActiveActionCssClass); + var isCompleted = (this.blackops[action.name] != null); + var estimatedSuccessChance = action.getSuccessChance(this, {est:true}); + var difficulty = action.getDifficulty(); + var actionTime = action.getActionTime(this); + var hasReqdRank = this.rank >= action.reqdRank; + + //UI for Completed Black Op + if (isCompleted) { + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { + innerText:action.name + " (COMPLETED)", display:"block", + })); + return; + } + + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header + innerText:isActive ? action.name + " (IN PROGRESS - " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeCurrent, 0) + " / " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.actionTimeToComplete, 0) + ")" + : action.name, + display:"inline-block", + })); + + if (isActive) { //Progress bar if its active + var progress = this.actionTimeCurrent / this.actionTimeToComplete; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + innerText:Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createProgressBarText"])({progress:progress}) + })); + } else { + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Start button + innerText:"Start", margin:"3px", padding:"3px", + class:hasReqdRank ? "a-link-button" : "a-link-button-inactive", + clickListener:()=>{ + this.action.type = ActionTypes.BlackOperation; + this.action.name = action.name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + return false; + } + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Set Team Size Button + innerText:"Set Team Size (Curr Size: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.teamCount, 0) + ")", class:"a-link-button", + margin:"3px", padding:"3px", + clickListener:()=>{ + var popupId = "bladeburner-operation-set-team-size-popup"; + var txt = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + innerText:"Enter the amount of team members you would like to take on this " + + "BlackOp. If you do not have the specified number of team members, " + + "then as many as possible will be used. Note that team members may " + + "be lost during operations." + + }); + var input = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("input", { + type:"number", placeholder: "Team Members" + }); + var setBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Confirm", class:"a-link-button", + clickListener:()=>{ + var num = Math.round(parseFloat(input.value)); + if (isNaN(num)) { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])("Invalid value entered for number of Team Members (must be numeric)") + } else { + action.teamCount = num; + this.updateBlackOpsUIElement(el, action); + } + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); + return false; + } + }); + var cancelBtn = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { + innerText:"Cancel", class:"a-link-button", + clickListener:()=>{ + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeElementById"])(popupId); + return false; + } + }); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createPopup"])(popupId, [txt, input, setBtn, cancelBtn]); + } + })); + } + + //Info + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"inline-block", + innerHTML:"
" + action.desc + "

", + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", color:hasReqdRank ? "white" : "red", + innerHTML:"Required Rank: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(action.reqdRank, 0) + "
" + })); + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"inline-block", + innerHTML:"Estimated Success Chance: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(estimatedSuccessChance*100, 1) + "%\n" + + "Time Required(s): " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(actionTime, 1), + })) +} + +Bladeburner.prototype.updateSkillsUIElement = function(el, skill) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["removeChildrenFromElement"])(el); + var skillName = skill.name; + var currentLevel = 0; + if (this.skills[skillName] && !isNaN(this.skills[skillName])) { + currentLevel = this.skills[skillName]; + } + var pointCost = skill.baseCost + (currentLevel * skill.costInc); + + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("h2", { //Header + innerText:skill.name + " (Lvl " + currentLevel + ")", display:"inline-block" + })); + + var canLevel = this.skillPoints >= pointCost; + var maxLvl = skill.maxLvl ? currentLevel >= skill.maxLvl : false; + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("a", { //Level up button + innerText:"Level", display:"inline-block", + class: canLevel && !maxLvl ? "a-link-button" : "a-link-button-inactive", + margin:"3px", padding:"3px", + clickListener:()=>{ + this.skillPoints -= pointCost; + this.upgradeSkill(skill); + this.createActionAndSkillsContent(); + return false; + } + })); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["appendLineBreaks"])(el, 2); + if (maxLvl) { + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + color:"red", display:"block", + innerText:"MAX LEVEL" + })); + } else { + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { + display:"block", + innerText:"Skill Points required: " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(pointCost, 0), + })); + } + el.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["createElement"])("p", { //Info/Description + innerHTML:skill.desc, display:"inline-block", + })); +} + +//Bladeburner Console Window +Bladeburner.prototype.postToConsole = function(input) { + if (input == null || DomElems.consoleDiv == null) {return;} + $("#bladeubrner-console-input-row").before('' + input + ''); + if (DomElems.consoleTable.childNodes.length > 200) { + DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); + } + this.updateConsoleScroll(); +} + +Bladeburner.prototype.updateConsoleScroll = function() { + DomElems.consoleDiv.scrollTop = DomElems.consoleDiv.scrollHeight; +} + +Bladeburner.prototype.resetConsoleInput = function() { + DomElems.consoleInput.value = ""; +} + +Bladeburner.prototype.clearConsole = function() { + while (DomElems.consoleTable.childNodes.length > 1) { + DomElems.consoleTable.removeChild(DomElems.consoleTable.firstChild); + } +} + +Bladeburner.prototype.log = function(input) { + //Adds a timestamp and then just calls postToConsole + var d = new Date(); + var timestamp = d.getMonth() + "/" + d.getDay() + " " + d.getHours() + ":" + d.getMinutes(); + this.postToConsole("[" + timestamp + "] " + input); +} + +//Handles a potential series of commands (comm1; comm2; comm3;) +Bladeburner.prototype.executeConsoleCommands = function(commands) { + try { + //Console History + if (consoleHistory[consoleHistory.length-1] != commands) { + consoleHistory.push(commands); + if (consoleHistory.length > 50) { + consoleHistory.splice(0, 1); + } + } + consoleHistoryIndex = consoleHistory.length; + + var arrayOfCommands = commands.split(";"); + for (var i = 0; i < arrayOfCommands.length; ++i) { + this.executeConsoleCommand(arrayOfCommands[i]); + } + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["exceptionAlert"])(e); + } +} + +//A single command +Bladeburner.prototype.executeConsoleCommand = function(command) { + command = command.trim(); + command = command.replace(/\s\s+/g, ' '); //Replace all whitespace w/ a single space + + var args = this.parseCommandArguments(command); + if (args.length <= 0) {return;} //Log an error? + + switch(args[0].toLowerCase()) { + case "automate": + this.executeAutomateConsoleCommand(args); + break; + case "clear": + case "cls": + this.clearConsole(); + break; + case "help": + this.executeHelpConsoleCommand(args); + break; + case "log": + this.executeLogConsoleCommand(args); + break; + case "skill": + this.executeSkillConsoleCommand(args); + break; + case "start": + this.executeStartConsoleCommand(args); + break; + case "stop": + this.resetAction(); + break; + default: + this.postToConsole("Invalid console command"); + break; + } +} + +Bladeburner.prototype.parseCommandArguments = function(command) { + //Returns an array with command and its arguments in each index. + //e.g. skill "blade's intuition" foo returns [skill, blade's intuition, foo] + //The input to this fn will be trimmed and will have all whitespace replaced w/ a single space + var args = []; + var start = 0, i = 0; + while (i < command.length) { + var c = command.charAt(i); + if (c === '"') { + var endQuote = command.indexOf('"', i+1); + if (endQuote !== -1 && (endQuote === command.length-1 || command.charAt(endQuote+1) === " ")) { + args.push(command.substr(i+1, (endQuote - i - 1))); + if (endQuote === command.length-1) { + start = i = endQuote+1; + } else { + start = i = endQuote+2; //Skip the space + } + continue; + } + } else if (c === " ") { + args.push(command.substr(start, i-start)); + start = i+1; + } + ++i; + } + if (start !== i) {args.push(command.substr(start, i-start));} + console.log("Bladeburner.parseCommandArguments returned: " + args); + return args; +} + +Bladeburner.prototype.executeAutomateConsoleCommand = function(args) { + if (args.length !== 2 && args.length !== 4) { + this.postToConsole("Invalid use of 'automate' command: automate [var] [val] [hi/low]. Use 'help automate' for more info"); + return; + } + + //Enable/Disable + if (args.length === 2) { + var flag = args[1]; + if (flag.toLowerCase() === "status") { + this.postToConsole("Automation: " + (this.automateEnabled ? "enabled" : "disabled")); + if (this.automateEnabled) { + this.postToConsole("When your stamina drops to " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.automateThreshLow, 0) + + ", you will automatically switch to " + this.automateActionLow.name + + ". When your stamina recovers to " + + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.automateThreshHigh, 0) + ", you will automatically " + + "switch to " + this.automateActionHigh.name + "."); + } + + } else if (flag.toLowerCase().includes("en")) { + if (!(this.automateActionLow instanceof ActionIdentifier) || + !(this.automateActionHigh instanceof ActionIdentifier)) { + return this.log("Failed to enable automation. Actions were not set"); + } + this.automateEnabled = true; + this.log("Bladeburner automation enabled"); + } else if (flag.toLowerCase().includes("d")) { + this.automateEnabled = false; + this.log("Bladeburner automation disabled"); + } else { + this.log("Invalid argument for 'automate' console command: " + args[1]); + } + return; + } + + //Set variables + if (args.length === 4) { + var variable = args[1], val = args[2]; + + var highLow = false; //True for high, false for low + if (args[3].toLowerCase().includes("hi")) {highLow = true;} + + switch (variable) { + case "general": + case "gen": + if (GeneralActions[val] != null) { + var action = new ActionIdentifier({ + type:ActionTypes[val], name:val + }); + if (highLow) { + this.automateActionHigh = action; + } else { + this.automateActionLow = action; + } + this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); + } else { + this.postToConsole("Invalid action name specified: " + val); + } + break; + case "contract": + case "contracts": + if (this.contracts[val] != null) { + var action = new ActionIdentifier({ + type:ActionTypes.Contract, name:val + }); + if (highLow) { + this.automateActionHigh = action; + } else { + this.automateActionLow = action; + } + this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); + } else { + this.postToConsole("Invalid contract name specified: " + val); + } + break; + case "ops": + case "op": + case "operations": + case "operation": + if (this.operations[val] != null) { + var action = new ActionIdentifier({ + type:ActionTypes.Operation, name:val + }); + if (highLow) { + this.automateActionHigh = action; + } else { + this.automateActionLow = action; + } + this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") action set to " + val); + } else { + this.postToConsole("Invalid Operation name specified: " + val); + } + break; + case "stamina": + if (isNaN(val)) { + this.postToConsole("Invalid value specified for stamina threshold (must be numeric): " + val); + } else { + if (highLow) { + this.automateThreshHigh = Number(val); + } else { + this.automateThreshLow = Number(val); + } + this.log("Automate (" + (highLow ? "HIGH" : "LOW") + ") stamina threshold set to " + val); + } + break; + default: + break; + } + + return; + } +} + +Bladeburner.prototype.executeHelpConsoleCommand = function(args) { + if (args.length === 1) { + this.postToConsole(consoleHelpText.helpList); + } else { + for (var i = 1; i < args.length; ++i) { + var commandText = consoleHelpText[args[i]]; + if (commandText != null) { + this.postToConsole(commandText); + this.postToConsole("
"); + } + } + } +} + +Bladeburner.prototype.executeLogConsoleCommand = function(args) { + if (args.length < 3) { + this.postToConsole("Invalid usage of log command: log [enable/disable] [action/event]"); + this.postToConsole("Use 'help log' for more details and examples"); + return; + } + + var flag = true; + if (args[1].toLowerCase().includes("d")) {flag = false;} //d for disable + + switch (args[2].toLowerCase()) { + case "general": + case "gen": + this.logging.general = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for general actions"); + break; + case "contract": + case "contracts": + this.logging.contracts = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for Contracts"); + break; + case "ops": + case "op": + case "operations": + case "operation": + this.logging.ops = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for Operations"); + break; + case "blackops": + case "blackop": + case "black operations": + case "black operation": + this.logging.blackops = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for BlackOps"); + break; + case "event": + case "events": + this.logging.events = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for events"); + break; + case "all": + this.logging.general = flag; + this.logging.contracts = flag; + this.logging.ops = flag; + this.logging.blackops = flag; + this.logging.events = flag; + this.log("Logging " + (flag ? "enabled" : "disabled") + " for everything"); + break; + default: + this.postToConsole("Invalid action/event type specified: " + args[2]); + this.postToConsole("Examples of valid action/event identifiers are: [general, contracts, ops, blackops, events]"); + break; + } +} + +Bladeburner.prototype.executeSkillConsoleCommand = function(args) { + switch (args.length) { + case 1: + //Display Skill Help Command + this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); + this.postToConsole("Use 'help skill' for more info"); + break; + case 2: + if (args[1].toLowerCase() === "list") { + //List all skills and their level + this.postToConsole("Skills: "); + var skillNames = Object.keys(Skills); + for(var i = 0; i < skillNames.length; ++i) { + var skill = Skills[skillNames[i]]; + var level = 0; + if (this.skills[skill.name] != null) {level = this.skills[skill.name];} + this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(level, 0)); + } + this.postToConsole(" "); + this.postToConsole("Effects: "); + var multKeys = Object.keys(this.skillMultipliers); + for (var i = 0; i < multKeys.length; ++i) { + var mult = this.skillMultipliers[multKeys[i]]; + if (mult && mult !== 1) { + mult = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(mult, 3); + switch(multKeys[i]) { + case "successChanceAll": + this.postToConsole("Total Success Chance: x" + mult); + break; + case "successChanceStealth": + this.postToConsole("Stealth Success Chance: x" + mult); + break; + case "successChanceKill": + this.postToConsole("Retirement Success Chance: x" + mult); + break; + case "successChanceContract": + this.postToConsole("Contract Success Chance: x" + mult); + break; + case "successChanceOperation": + this.postToConsole("Operation Success Chance: x" + mult); + break; + case "successChanceEstimate": + this.postToConsole("Synthoid Data Estimate: x" + mult); + break; + case "actionTime": + this.postToConsole("Action Time: x" + mult); + break; + case "effHack": + this.postToConsole("Hacking Skill: x" + mult); + break; + case "effStr": + this.postToConsole("Strength: x" + mult); + break; + case "effDef": + this.postToConsole("Defense: x" + mult); + break; + case "effDex": + this.postToConsole("Dexterity: x" + mult); + break; + case "effAgi": + this.postToConsole("Agility: x" + mult); + break; + case "effCha": + this.postToConsole("Charisma: x" + mult); + break; + case "effInt": + this.postToConsole("Intelligence: x" + mult); + break; + case "stamina": + this.postToConsole("Stamina: x" + mult); + break; + case "weaponAbility": + //DomElems.actionsAndSkillsDesc.innerHTML += + break; + case "gunAbility": + //DomElems.actionsAndSkillsDesc.innerHTML + break; + default: + console.log("Warning: Unrecognized SkillMult Key: " + multKeys[i]); + break; + } + } + } + } else { + this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); + this.postToConsole("Use 'help skill' for more info"); + } + break; + case 3: + var skillName = args[2]; + var skill = Skills[skillName]; + if (skill == null || !(skill instanceof Skill)) { + return this.postToConsole("Invalid skill name (Note that this is case-sensitive): " + skillName); + } + if (args[1].toLowerCase() === "list") { + this.postToConsole(skill.name + ": Level " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(this.skills[skill.name]), 0); + } else if (args[1].toLowerCase() === "level") { + var currentLevel = 0; + if (this.skills[skillName] && !isNaN(this.skills[skillName])) { + currentLevel = this.skills[skillName]; + } + var pointCost = skill.baseCost + (currentLevel * skill.costInc); + if (this.skillPoints >= pointCost) { + this.skillPoints -= pointCost; + this.upgradeSkill(skill); + this.log(skill.name + " upgraded to Level " + this.skills[skillName]); + this.createActionAndSkillsContent(); + } else { + this.postToConsole("You do not have enough Skill Points to upgrade this. You need " + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_11__["formatNumber"])(pointCost, 0)); + } + + } else { + this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); + this.postToConsole("Use 'help skill' for more info"); + } + break; + default: + this.postToConsole("Invalid usage of 'skill' console command: skill [action] [name]"); + this.postToConsole("Use 'help skill' for more info"); + break; + } +} + +Bladeburner.prototype.executeStartConsoleCommand = function(args) { + if (args.length !== 3) { + this.postToConsole("Invalid usage of 'start' console command: start [type] [name]"); + this.postToConsole("Use 'help start' for more info"); + return; + } + var name = args[2]; + switch (args[1].toLowerCase()) { + case "general": + case "gen": + if (GeneralActions[name] != null) { + this.action.type = ActionTypes[name]; + this.action.name = name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + } else { + this.postToConsole("Invalid action name specified: " + args[2]); + } + break; + case "contract": + case "contracts": + if (this.contracts[name] != null) { + this.action.type = ActionTypes.Contract; + this.action.name = name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + } else { + this.postToConsole("Invalid contract name specified: " + args[2]); + } + break; + case "ops": + case "op": + case "operations": + case "operation": + if (this.operations[name] != null) { + this.action.type = ActionTypes.Operation; + this.action.name = name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + } else { + this.postToConsole("Invalid Operation name specified: " + args[2]); + } + break; + case "blackops": + case "blackop": + case "black operations": + case "black operation": + if (BlackOperations[name] != null) { + this.action.type = ActionTypes.BlackOperation; + this.action.name = name; + this.startAction(this.action); + this.updateActionAndSkillsContent(); + } else { + this.postToConsole("Invalid BlackOp name specified: " + args[2]); + } + break; + default: + this.postToConsole("Invalid action/event type specified: " + args[1]); + this.postToConsole("Examples of valid action/event identifiers are: [general, contract, op, blackop]"); + break; + } +} + + +Bladeburner.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_toJSON"])("Bladeburner", this); +} +Bladeburner.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Generic_fromJSON"])(Bladeburner, value.data); +} +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_9__["Reviver"].constructors.Bladeburner = Bladeburner; + +//This initialized Bladeburner-related data that is NOT saved/loaded +// eg: Skill Objects, BLack Operations +//Any data that is saved/loaded should go in Bladeburner object +// eg: contracts, operations +function initBladeburner() { + //Skills + Skills[SkillNames.BladesIntuition] = new Skill({ + name:SkillNames.BladesIntuition, + desc:"Each level of this skill increases your success chance " + + "for all contracts and operations by 3%", + baseCost:5, costInc:2, + successChanceAll:3 + }); + Skills[SkillNames.Reaper] = new Skill({ + name:SkillNames.Reaper, + desc:"Each level of this skill increases your " + + "effective combat stats for Bladeburner actions by 3%", + baseCost:3, costInc:2, + effStr:3, effDef:3, effDex:3, effAgi:3 + }); + Skills[SkillNames.Cloak] = new Skill({ + name:SkillNames.Cloak, + desc:"Each level of this skill increases your " + + "success chance in stealth-related contracts and operations by 5.5%", + baseCost:3, costInc:1, + successChanceStealth:5.5 + }); + + //TODO Marksman + //TODO Weapon Proficiency + + Skills[SkillNames.Overclock] = new Skill({ + name:SkillNames.Overclock, + desc:"Each level of this skill decreases the time it takes " + + "to attempt a contract or operation by 1% (Max Level: 95)", + baseCost:5, costInc:1, maxLvl:95, + actionTime:1 + }); + Skills[SkillNames.EvasiveSystem] = new Skill({ + name:SkillNames.EvasiveSystem, + desc:"Each level of this skill increases your effective " + + "dexterity and agility for Bladeburner actions by 5%", + baseCost:2, costInc: 1, + effDex:5, effAgi:5 + }); + Skills[SkillNames.ShortCircuit] = new Skill({ + name:SkillNames.ShortCircuit, + desc:"Each level of this skill increases your success chance " + + "in contracts and operations that involve retirement by 5.5%", + baseCost:3, costInc:2, + successChanceKill:5.5 + }); + Skills[SkillNames.DigitalObserver] = new Skill({ + name:SkillNames.DigitalObserver, + desc:"Each level of this skill increases your success chance in " + + "all operations by 4%", + baseCost:5, costInc:2, + successChanceOperation:4 + }); + Skills[SkillNames.Datamancer] = new Skill({ + name:SkillNames.Datamancer, + desc:"Each level of this skill increases your effectiveness in " + + "synthoid population analysis and investigation by 5%. " + + "This affects all actions that can potentially increase " + + "the accuracy of your synthoid population/community estimates.", + baseCost:3,costInc:1, + successChanceEstimate:5 + }); + Skills[SkillNames.Tracer] = new Skill({ + name:SkillNames.Tracer, + desc:"Each level of this skill increases your success chance in " + + "all contracts by 4%", + baseCost:3, costInc:2, + successChanceContract:4 + }); + Skills[SkillNames.CybersEdge] = new Skill({ + name:SkillNames.CybersEdge, + desc:"Each level of this skill increases your max " + + "stamina by 2%", + baseCost:1, costInc:3, + stamina:2 + }); + + //General Actions + var actionName = "Training"; + GeneralActions[actionName] = new Action({ + name:actionName, + desc:"Improve your abilities at the Bladeburner unit's specialized training " + + "center. Doing this gives experience for all combat stats and also " + + "increases your max stamina." + }); + + var actionName = "Field Analysis"; + GeneralActions[actionName] = new Action({ + name:actionName, + desc:"Mine and analyze Synthoid-related data. This improve the " + + "Bladeburner's unit intelligence on Synthoid locations and " + + "activities. Completing this action will improve the accuracy " + + "of your Synthoid population estimated in the current city.

" + + "Does NOT require stamina." + }); + + var actionName = "Recruitment"; + GeneralActions[actionName] = new Action({ + name:actionName, + desc:"Attempt to recruit members for your Bladeburner team. These members " + + "can help you conduct operations.

" + + "Does NOT require stamina." + }); + + //Black Operations + BlackOperations["Operation Typhoon"] = new BlackOperation({ + name:"Operation Typhoon", + desc:"Obadiah Zenyatta is the leader of a RedWater PMC. It has long " + + "been known among the intelligence community that Zenyatta, along " + + "with the rest of the PMC, is a Synthoid.

" + + "The goal of Operation Typhoon is to find and eliminate " + + "Zenyatta and RedWater by any means necessary. After the task " + + "is completed, the actions must be covered up from the general public.", + baseDifficulty:2000, reqdRank:2.5e3, + rankGain:25, rankLoss:10, hpLoss:100, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Zero"] = new BlackOperation({ + name:"Operation Zero", + desc:"AeroCorp is one of the world's largest defense contractors. " + + "It's leader, Steve Watataki, is thought to be a supporter of " + + "Synthoid rights. He must be removed.

" + + "The goal of Operation Zero is to covertly infiltrate AeroCorp and " + + "uncover any incriminating evidence or " + + "information against Watataki that will cause him to be removed " + + "from his position at AeroCorp. Incriminating evidence can be " + + "fabricated as a last resort. Be warned that AeroCorp has some of " + + "the most advanced security measures in the world.", + baseDifficulty:2500, reqdRank:5e3, + rankGain:30, rankLoss:15, hpLoss:50, + weights:{hack:0.2,str:0.15,def:0.15,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isStealth:true + }); + BlackOperations["Operation X"] = new BlackOperation({ + name:"Operation X", + desc:"We have recently discovered an underground publication " + + "group called Samizdat. Even though most of their publications " + + "are nonsensical conspiracy theories, the average human is " + + "gullible enough to believe them. Many of their works discuss " + + "Synthoids and pose a threat to society. The publications are spreading " + + "rapidly in China and other Eastern countries.

" + + "Samizdat has done a good job of keeping hidden and anonymous. " + + "However, we've just received intelligence that their base of " + + "operations is in Ishima's underground sewer systems. Your task is to " + + "investigate the sewer systems, and eliminate Samizdat. They must " + + "never publish anything again.", + baseDifficulty:3000, reqdRank:7.5e3, + rankGain:30, rankLoss:15, hpLoss:100, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Titan"] = new BlackOperation({ + name:"Operation Titan", + desc:"Several months ago Titan Laboratories' Bioengineering department " + + "was infiltrated by Synthoids. As far as we know, Titan Laboratories' " + + "management has no knowledge about this. We don't know what the " + + "Synthoids are up to, but the research that they could " + + "be conducting using Titan Laboraties' vast resources is potentially " + + "very dangerous.

" + + "Your goal is to enter and destroy the Bioengineering department's " + + "facility in Aevum. The task is not just to retire the Synthoids there, but " + + "also to destroy any information or research at the facility that " + + "is relevant to the Synthoids and their goals.", + baseDifficulty:4000, reqdRank:10e3, + rankGain:40, rankLoss:20, hpLoss:100, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Ares"] = new BlackOperation({ + name:"Operation Ares", + desc:"One of our undercover agents, Agent Carter, has informed us of a " + + "massive weapons deal going down in Dubai between rogue Russian " + + "militants and a radical Synthoid community. These weapons are next-gen " + + "plasma and energy weapons. It is critical for the safety of humanity " + + "that this deal does not happen.

" + + "Your task is to intercept the deal. Leave no survivors.", + baseDifficulty:5000, reqdRank:12.5e3, + rankGain:40, rankLoss:20, hpLoss:200, + weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0}, + decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Archangel"] = new BlackOperation({ + name:"Operation Archangel", + desc:"Our analysts have discovered that the popular Red Rabbit brothel in " + + "Amsterdam is run and 'staffed' by MK-VI Synthoids. Intelligence " + + "suggests that the profit from this brothel is used to fund a large " + + "black market arms trafficking operation.

" + + "The goal of this operation is to take out the leaders that are running " + + "the Red Rabbit brothel. Try to limit the number of other casualties, " + + "but do what you must to complete the mission.", + baseDifficulty:7500, reqdRank:15e3, + rankGain:50, rankLoss:20, hpLoss:25, + weights:{hack:0,str:0.2,def:0.2,dex:0.3,agi:0.3,cha:0, int:0}, + decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true, + }); + BlackOperations["Operation Juggernaut"] = new BlackOperation({ + name:"Operation Juggernaut", + desc:"The CIA has just encountered a new security threat. A new " + + "criminal group, lead by a shadowy operative who calls himself " + + "Juggernaut, has been smuggling drugs and weapons (including " + + "suspected bioweapons) into Sector-12. We also have reason " + + "to believe the tried to break into one of Universal Energy's " + + "facilities in order to cause a city-wide blackout. The CIA " + + "suspects that Juggernaut is a heavily-augmented Synthoid, and " + + "have thus enlisted our help.

" + + "Your mission is to eradicate Juggernaut and his followers.", + baseDifficulty:10e3, reqdRank:20e3, + rankGain:75, rankLoss:40, hpLoss:300, + weights:{hack:0,str:0.25,def:0.25,dex:0.25,agi:0.25,cha:0, int:0}, + decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true, + }); + BlackOperations["Operation Red Dragon"] = new BlackOperation({ + name:"Operation Red Dragon", + desc:"The Tetrads criminal organization is suspected of " + + "reverse-engineering the MK-VI Synthoid design. We believe " + + "they altered and possibly improved the design and began " + + "manufacturing their own Synthoid models in order to bolster " + + "their criminal activities.

" + + "Your task is to infiltrate and destroy the Tetrads' base of operations " + + "in Los Angeles. Intelligence tells us that their base houses " + + "one of their Synthoid manufacturing units.", + baseDifficulty:12.5e3, reqdRank:25e3, + rankGain:100, rankLoss:50, hpLoss:500, + weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true, + }); + BlackOperations["Operation K"] = new BlackOperation({ + name:"Operation K", + desc:"CODE RED SITUATION. Our intelligence tells us that VitaLife " + + "has discovered a new android cloning technology. This technology " + + "is supposedly capable of cloning Synthoid, not only physically " + + "but also their advanced AI modules. We do not believe that " + + "VitaLife is trying to use this technology illegally or " + + "maliciously, but if any Synthoids were able to infiltrate the " + + "corporation and take advantage of this technology then the " + + "results would be catastrophic.

" + + "We do not have the power or jurisdiction to shutdown this down " + + "through legal or political means, so we must resort to a covert " + + "operation. Your goal is to destroy this technology and eliminate" + + "anyone who was involved in its creation.", + baseDifficulty:15e3, reqdRank:30e3, + rankGain:120, rankLoss:60, hpLoss:1000, + weights:{hack:0.05,str:0.2,def:0.2,dex:0.25,agi:0.25,cha:0, int:0.05}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Deckard"] = new BlackOperation({ + name:"Operation Deckard", + desc:"Despite your success in eliminating VitaLife's new android-replicating " + + "technology in Operation K, we've discovered that a small group of " + + "MK-VI Synthoids were able to make off with the schematics and design " + + "of the technology before the Operation. It is almost a certainty that " + + "these Synthoids are some of the rogue MK-VI ones from the Synthoid Uprising." + + "The goal of Operation Deckard is to hunt down these Synthoids and retire " + + "them. I don't need to tell you how critical this mission is.", + baseDifficulty:20e3, reqdRank:40e3, + rankGain:150, rankLoss:75, hpLoss:200, + weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, + decays:{hack:0,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true, + }); + BlackOperations["Operation Tyrell"] = new BlackOperation({ + name:"Operation Tyrell", + desc:"A week ago Blade Industries reported a small break-in at one " + + "of their Aevum Augmentation storage facitilities. We figured out " + + "that The Dark Army was behind the heist, and didn't think any more " + + "of it. However, we've just discovered that several known MK-VI Synthoids " + + "were part of that break-in group.

" + + "We cannot have Synthoids upgrading their already-enhanced abilities " + + "with Augmentations. Your task is to hunt down the associated Dark Army " + + "members and eliminate them.", + baseDifficulty:25e3, reqdRank:50e3, + rankGain:200, rankLoss:100, hpLoss:500, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true, + }); + BlackOperations["Operation Wallace"] = new BlackOperation({ + name:"Operation Wallace", + desc:"Based on information gathered from Operation Tyrell, we've discovered " + + "that The Dark Army was well aware that there were Synthoids amongst " + + "their ranks. Even worse, we believe that The Dark Army is working " + + "together with other criminal organizations such as The Syndicate and " + + "that they are planning some sort of large-scale takeover of multiple major " + + "cities, most notably Aevum. We suspect that Synthoids have infiltrated " + + "the ranks of these criminal factions and are trying to stage another " + + "Synthoid uprising.

" + + "The best way to deal with this is to prevent it before it even happens. " + + "The goal of Operation Wallace is to destroy the Dark Army and " + + "Syndicate factions in Aevum immediately. Leave no survivors.", + baseDifficulty:30e3, reqdRank:75e3, + rankGain:500, rankLoss:150, hpLoss:1500, + weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Shoulder of Orion"] = new BlackOperation({ + name:"Operation Shoulder of Orion", + desc:"China's Solaris Space Systems is secretly launching the first " + + "manned spacecraft in over a decade using Synthoids. We believe " + + "China is trying to establish the first off-world colonies.

" + + "The mission is to prevent this launch without instigating an " + + "international conflict. When you accept this mission you will be " + + "officially disavowed by the NSA and the national government until after you " + + "successfully return. In the event of failure, all of the operation's " + + "team members must not let themselves be captured alive.", + baseDifficulty:35e3, reqdRank:100e3, + rankGain:1e3, rankLoss:500, hpLoss:1500, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isStealth:true + }); + BlackOperations["Operation Hyron"] = new BlackOperation({ + name:"Operation Hyron", + desc:"Our intelligence tells us that Fulcrum Technologies is developing " + + "a quantum supercomputer using human brains as core " + + "processors. This supercomputer " + + "is rumored to be able to store vast amounts of data and " + + "perform computations unmatched by any other supercomputer on the " + + "planet. But more importantly, the use of organic human brains " + + "means that the supercomputer may be able to reason abstractly " + + "and become self-aware.

" + + "I do not need to remind you why sentient-level AIs pose a serious " + + "thread to all of mankind.

" + + "The research for this project is being conducted at one of Fulcrum " + + "Technologies secret facilities in Aevum, codenamed 'Alpha Ranch'. " + + "Infiltrate the compound, delete and destroy the work, and then find and kill the " + + "project lead.", + baseDifficulty:40e3, reqdRank:125e3, + rankGain:2e3, rankLoss:1e3, hpLoss:500, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Morpheus"] = new BlackOperation({ + name:"Operation Morpheus", + desc:"DreamSense Technologies is an advertising company that uses " + + "special technology to transmit their ads into the peoples " + + "dreams and subconcious. They do this using broadcast transmitter " + + "towers. Based on information from our agents and informants in " + + "Chonqging, we have reason to believe that one of the broadcast " + + "towers there has been compromised by Synthoids and is being used " + + "to spread pro-Synthoid propaganda.

" + + "The mission is to destroy this broadcast tower. Speed and " + + "stealth are of the upmost important for this.", + baseDifficulty:45e3, reqdRank:150e3, + rankGain:5e3, rankLoss:1e3, hpLoss:100, + weights:{hack:0.05,str:0.15,def:0.15,dex:0.3,agi:0.3,cha:0, int:0.05}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isStealth:true + }); + BlackOperations["Operation Ion Storm"] = new BlackOperation({ + name:"Operation Ion Storm", + desc:"Our analysts have uncovered a gathering of MK-VI Synthoids " + + "that have taken up residence in the Sector-12 Slums. We " + + "don't know if they are rogue Synthoids from the Uprising, " + + "but we do know that they have been stockpiling " + + "weapons, money, and other resources. This makes them dangerous.

" + + "This is a full-scale assault operation to find and retire all of these " + + "Synthoids in the Sector-12 Slums.", + baseDifficulty:50e3, reqdRank:175e3, + rankGain:5e3, rankLoss:1e3, hpLoss:5000, + weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Annihilus"] = new BlackOperation({ + name:"Operation Annihilus", + desc:"Our superiors have ordered us to eradicate everything and everyone " + + "in an underground facility located in Aevum. They tell us " + + "that the facility houses many dangerous Synthoids and " + + "belongs to a terrorist organization called " + + "'The Covenant'. We have no prior intelligence about this " + + "organization, so you are going in blind.", + baseDifficulty:55e3, reqdRank:200e3, + rankGain:5e3, rankLoss:1e3, hpLoss:10e3, + weights:{hack:0,str:0.24,def:0.24,dex:0.24,agi:0.24,cha:0, int:0.04}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Ultron"] = new BlackOperation({ + name:"Operation Ultron", + desc:"OmniTek Incorporated, the original designer and manufacturer of Synthoids, " + + "has notified us of a malfunction in their AI design. This malfunction, " + + "when triggered, causes MK-VI Synthoids to become radicalized and seek out " + + "the destruction of humanity. They say that this bug affects all MK-VI Synthoids, " + + "not just the rogue ones from the Uprising.

" + + "OmniTek has also told us they they believe someone has triggered this " + + "malfunction in a large group of MK-VI Synthoids, and that these newly-radicalized Synthoids " + + "are now amassing in Volhaven to form a terrorist group called Ultron.

" + + "Intelligence suggests Ultron is heavily armed and that their members are " + + "augmented. We believe Ultron is making moves to take control of " + + "and weaponize DeltaOne's Tactical High-Energy Satellite Laser Array (THESLA).

" + + "Your task is to find and destroy Ultron.", + baseDifficulty:60e3, reqdRank:250e3, + rankGain:10e3, rankLoss:2e3, hpLoss:10e3, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + isKill:true + }); + BlackOperations["Operation Centurion"] = new BlackOperation({ + name:"Operation Centurion", + desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)

" + + "Throughout all of humanity's history, we have relied on " + + "technology to survive, conquer, and progress. Its advancement became our primary goal. " + + "And at the peak of human civilization technology turned into " + + "power. Global, absolute power.

" + + "It seems that the universe is not without a sense of irony.

" + + "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", + baseDifficulty:70e3, reqdRank:300e3, + rankGain:15e3, rankLoss:5e3, hpLoss:10e3, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + }); + BlackOperations["Operation Vindictus"] = new BlackOperation({ + name:"Operation Vindictus", + desc:"D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)

" + + "The bits are all around us. The daemons that hold the Node " + + "together can manifest themselves in many different ways.

" + + "D)@#)($M)C0293c40($*)@#D0JUMP3Rm0C<*@#)*$)#02c94830c(#$*D)", + baseDifficulty:75e3, reqdRank:350e3, + rankGain:20e3, rankLoss:20e3, hpLoss:20e3, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + }); + BlackOperations["Operation Daedalus"] = new BlackOperation({ + name:"Operation Daedalus", + desc:"Yesterday we obeyed kings and bent our neck to emperors. " + + "Today we kneel only to truth.", + baseDifficulty:80e3, reqdRank:400e3, + rankGain:40e3, rankLoss:10e3, hpLoss:100e3, + weights:{hack:0.1,str:0.2,def:0.2,dex:0.2,agi:0.2,cha:0, int:0.1}, + decays:{hack:0.6,str:0.8,def:0.8,dex:0.8,agi:0.8,cha:0, int:0.75}, + }); +} + + + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) + +/***/ }), +/* 41 */ /*!************************!*\ !*** ./src/RedPill.js ***! \************************/ @@ -58428,15 +56838,15 @@ function applySourceFile(srcFile) { __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "redPillFlag", function() { return redPillFlag; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hackWorldDaemon", function() { return hackWorldDaemon; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.js */ 5); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Prestige.js */ 57); -/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SourceFile.js */ 44); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _Prestige_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Prestige.js */ 53); +/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SourceFile.js */ 37); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -58764,74 +57174,313 @@ function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode, flume=fa -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 46 */ -/*!******************************!*\ - !*** ./src/NetscriptPort.js ***! - \******************************/ +/* 42 */ +/*!********************************!*\ + !*** ./src/ActiveScriptsUI.js ***! + \********************************/ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPort", function() { return NetscriptPort; }); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Settings.js */ 23); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addActiveScriptsItem", function() { return addActiveScriptsItem; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteActiveScriptsItem", function() { return deleteActiveScriptsItem; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateActiveScriptsItems", function() { return updateActiveScriptsItems; }); +/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.js */ 5); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); +/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/LogBox.js */ 47); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! numeral/min/numeral.min */ 10); +/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -function NetscriptPort() { - this.data = []; -} -NetscriptPort.prototype.write = function(data) { - this.data.push(data); - if (this.data.length > _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) { - return this.data.shift(); + + + + + + + +/* { + * serverName: { + * header: Server Header Element + * panel: Server Panel List (ul) element + * scripts: { + * script id: Ref to Script information + * } + * } + * ... + */ +let ActiveScriptsUI = {}; +let ActiveScriptsTasks = []; //Sequentially schedule the creation/deletion of UI elements + +function createActiveScriptsServerPanel(server) { + let hostname = server.hostname; + + var activeScriptsList = document.getElementById("active-scripts-list"); + + let res = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({hdrText:hostname}); + let li = res[0]; + var hdr = res[1]; + let panel = res[2]; + + if (ActiveScriptsUI[hostname] != null) { + console.log("WARNING: Tried to create already-existing Active Scripts Server panel. This is most likely fine. It probably means many scripts just got started up on a new server. Aborting"); + return; } - return null; + + var panelScriptList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("ul"); + panel.appendChild(panelScriptList); + activeScriptsList.appendChild(li); + + ActiveScriptsUI[hostname] = { + header: hdr, + panel: panel, + panelList: panelScriptList, + scripts: {}, //Holds references to li elements for each active script + scriptHdrs: {}, //Holds references to header elements for each active script + scriptStats: {} //Holds references to the p elements containing text for each active script + }; + + return li; } -NetscriptPort.prototype.tryWrite = function(data) { - if (this.data.length >= _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) { - return false; +//Deletes the info for a particular server (Dropdown header + Panel with all info) +//in the Active Scripts page if it exists +function deleteActiveScriptsServerPanel(server) { + let hostname = server.hostname; + if (ActiveScriptsUI[hostname] == null) { + console.log("WARNING: Tried to delete non-existent Active Scripts Server panel. Aborting"); + return; } - this.data.push(data); - return true; -} -NetscriptPort.prototype.read = function() { - if (this.data.length === 0) { - return "NULL PORT DATA"; + //Make sure it's empty + if (Object.keys(ActiveScriptsUI[hostname].scripts).length > 0) { + console.log("WARNING: Tried to delete Active Scripts Server panel that still has scripts. Aborting"); + return; } - return this.data.shift(); + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(ActiveScriptsUI[hostname].panel); + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(ActiveScriptsUI[hostname].header); + delete ActiveScriptsUI[hostname]; } -NetscriptPort.prototype.peek = function() { - if (this.data.length === 0) { - return "NULL PORT DATA"; - } else { - var foo = this.data.slice(); - return foo[0]; +function addActiveScriptsItem(workerscript) { + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); + if (server == null) { + console.log("ERROR: Invalid server IP for workerscript in addActiveScriptsItem()"); + return; } + let hostname = server.hostname; + + ActiveScriptsTasks.push(function(workerscript, hostname) { + if (ActiveScriptsUI[hostname] == null) { + createActiveScriptsServerPanel(server); + } + + //Create the unique identifier (key) for this script + var itemNameArray = ["active", "scripts", hostname, workerscript.name]; + for (var i = 0; i < workerscript.args.length; ++i) { + itemNameArray.push(String(workerscript.args[i])); + } + var itemName = itemNameArray.join("-"); + + let res = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createAccordionElement"])({hdrText:workerscript.name}); + let li = res[0]; + let hdr = res[1]; + let panel = res[2]; + + hdr.classList.remove("accordion-header"); + hdr.classList.add("active-scripts-script-header"); + panel.classList.remove("accordion-panel"); + panel.classList.add("active-scripts-script-panel"); + + //Handle the constant elements on the panel that don't change after creation + //Threads, args, kill/log button + panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { + innerHTML: "Threads: " + workerscript.scriptRef.threads + "
" + + "Args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["printArray"])(workerscript.args) + })); + var panelText = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("p", { + innerText:"Loading...", fontSize:"14px", + }); + panel.appendChild(panelText); + panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("br")); + panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("span", { + innerText:"Log", class:"active-scripts-button", margin:"4px", padding:"4px", + clickListener:()=>{ + Object(_utils_LogBox_js__WEBPACK_IMPORTED_MODULE_6__["logBoxCreate"])(workerscript.scriptRef); + return false; + } + })); + panel.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["createElement"])("span", { + innerText:"Kill Script", class:"active-scripts-button", margin:"4px", padding:"4px", + clickListener:()=>{ + Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["killWorkerScript"])(workerscript.scriptRef, workerscript.scriptRef.scriptRef.server); + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Killing script, may take a few minutes to complete..."); + return false; + } + })); + + //Append element to list + ActiveScriptsUI[hostname]["panelList"].appendChild(li); + ActiveScriptsUI[hostname].scripts[itemName] = li; + ActiveScriptsUI[hostname].scriptHdrs[itemName] = hdr; + ActiveScriptsUI[hostname].scriptStats[itemName] = panelText; + }.bind(null, workerscript, hostname)); } -NetscriptPort.prototype.full = function() { - return this.data.length == _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity; +function deleteActiveScriptsItem(workerscript) { + ActiveScriptsTasks.push(function(workerscript) { + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); + if (server == null) { + throw new Error("ERROR: Invalid server IP for workerscript. This most likely occurred because " + + "you tried to delete a large number of scripts and also deleted servers at the " + + "same time. It's not a big deal, just save and refresh the game."); + return; + } + let hostname = server.hostname; + if (ActiveScriptsUI[hostname] == null) { + console.log("ERROR: Trying to delete Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname); + return; + } + + var itemNameArray = ["active", "scripts", server.hostname, workerscript.name]; + for (var i = 0; i < workerscript.args.length; ++i) { + itemNameArray.push(String(workerscript.args[i])); + } + var itemName = itemNameArray.join("-"); + + let li = ActiveScriptsUI[hostname].scripts[itemName]; + if (li == null) { + console.log("ERROR: Cannot find Active Script UI element for workerscript: "); + console.log(workerscript); + return; + } + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeElement"])(li); + delete ActiveScriptsUI[hostname].scripts[itemName]; + delete ActiveScriptsUI[hostname].scriptHdrs[itemName]; + delete ActiveScriptsUI[hostname].scriptStats[itemName]; + if (Object.keys(ActiveScriptsUI[hostname].scripts).length === 0) { + deleteActiveScriptsServerPanel(server); + } + }.bind(null, workerscript)); } -NetscriptPort.prototype.empty = function() { - return this.data.length === 0; +//Update the ActiveScriptsItems array +function updateActiveScriptsItems(maxTasks=100) { + //Run tasks that need to be done sequentially (adding items, creating/deleting server panels) + //We'll limit this to 50 at a time in case someone decides to start a bunch of scripts all at once... + let numTasks = Math.min(maxTasks, ActiveScriptsTasks.length); + for (let i = 0; i < numTasks; ++i) { + let task = ActiveScriptsTasks.shift(); + try { + task(); + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["exceptionAlert"])(e); + console.log(task); + } + } + + if (_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].currentPage !== _engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Page.ActiveScripts) {return;} + var total = 0; + for (var i = 0; i < _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["workerScripts"].length; ++i) { + try { + total += updateActiveScriptsItemContent(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_1__["workerScripts"][i]); + } catch(e) { + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["exceptionAlert"])(e); + } + } + document.getElementById("active-scripts-total-prod").innerHTML = + "Total online production of Active Scripts: " + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(total).format('$0.000a') + " / sec
" + + "Total online production since last Aug installation: " + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].scriptProdSinceLastAug).format('$0.000a') + " (" + + numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_7___default()(_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_2__["Player"].playtimeSinceLastAug/1000)).format('$0.000a') + " / sec)"; + return total; } -NetscriptPort.prototype.clear = function() { - this.data.length = 0; +//Updates the content of the given item in the Active Scripts list +function updateActiveScriptsItemContent(workerscript) { + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); + if (server == null) { + console.log("ERROR: Invalid server IP for workerscript."); + return; + } + let hostname = server.hostname; + if (ActiveScriptsUI[hostname] == null) { + return; //Hasn't been created yet. We'll skip it + } + + var itemNameArray = ["active", "scripts", server.hostname, workerscript.name]; + for (var i = 0; i < workerscript.args.length; ++i) { + itemNameArray.push(String(workerscript.args[i])); + } + var itemName = itemNameArray.join("-"); + + if (ActiveScriptsUI[hostname].scriptStats[itemName] == null) { + return; //Hasn't been fully added yet. We'll skip it + } + var item = ActiveScriptsUI[hostname].scriptStats[itemName]; + + //Update the text if necessary. This fn returns the online $/s production + return updateActiveScriptsText(workerscript, item, itemName); +} + +function updateActiveScriptsText(workerscript, item, itemName) { + var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_3__["getServer"])(workerscript.serverIp); + if (server == null) { + console.log("ERROR: Invalid server IP for workerscript."); + return; + } + let hostname = server.hostname; + if (ActiveScriptsUI[hostname] == null || ActiveScriptsUI[hostname].scriptHdrs[itemName] == null) { + console.log("ERROR: Trying to update Active Script UI Element with a hostname that cant be found in ActiveScriptsUI: " + hostname); + return; + } + + var onlineMps = workerscript.scriptRef.onlineMoneyMade / workerscript.scriptRef.onlineRunningTime; + + //Only update if the item is visible + if (ActiveScriptsUI[hostname].header.classList.contains("active") === false) {return onlineMps;} + if (ActiveScriptsUI[hostname].scriptHdrs[itemName].classList.contains("active") === false) {return onlineMps;} + + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["removeChildrenFromElement"])(item); + + //Online + var onlineTotalMoneyMade = "Total online production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.onlineMoneyMade, 2); + var onlineTotalExpEarned = (Array(26).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.onlineExpGained, 2) + " hacking exp").replace( / /g, " "); + + var onlineMpsText = "Online production rate: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(onlineMps, 2) + "/second"; + var onlineEps = workerscript.scriptRef.onlineExpGained / workerscript.scriptRef.onlineRunningTime; + var onlineEpsText = (Array(25).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(onlineEps, 4) + " hacking exp/second").replace( / /g, " "); + + //Offline + var offlineTotalMoneyMade = "Total offline production: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.offlineMoneyMade, 2); + var offlineTotalExpEarned = (Array(27).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(workerscript.scriptRef.offlineExpGained, 2) + " hacking exp").replace( / /g, " "); + + var offlineMps = workerscript.scriptRef.offlineMoneyMade / workerscript.scriptRef.offlineRunningTime; + var offlineMpsText = "Offline production rate: $" + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(offlineMps, 2) + "/second"; + var offlineEps = workerscript.scriptRef.offlineExpGained / workerscript.scriptRef.offlineRunningTime; + var offlineEpsText = (Array(26).join(" ") + Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_8__["formatNumber"])(offlineEps, 4) + " hacking exp/second").replace( / /g, " "); + + item.innerHTML = onlineTotalMoneyMade + "
" + onlineTotalExpEarned + "
" + + onlineMpsText + "
" + onlineEpsText + "
" + offlineTotalMoneyMade + "
" + offlineTotalExpEarned + "
" + + offlineMpsText + "
" + offlineEpsText + "
"; + return onlineMps; } /***/ }), -/* 47 */ +/* 43 */ /*!***************************!*\ !*** ./src/SaveObject.js ***! \***************************/ @@ -58841,27 +57490,27 @@ NetscriptPort.prototype.clear = function() { __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "saveObject", function() { return saveObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadGame", function() { return loadGame; }); -/* harmony import */ var _Alias_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias.js */ 30); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company.js */ 9); +/* harmony import */ var _Alias_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Alias.js */ 25); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Company.js */ 8); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf.js */ 33); -/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Gang.js */ 37); -/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./HacknetNode.js */ 40); -/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Message.js */ 29); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Fconf_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Fconf.js */ 30); +/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Gang.js */ 33); +/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./HacknetNode.js */ 38); +/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Message.js */ 27); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Script.js */ 26); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Settings.js */ 23); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./StockMarket.js */ 22); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_GameOptions_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/GameOptions.js */ 54); +/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Script.js */ 24); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Settings.js */ 19); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./StockMarket.js */ 29); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_GameOptions_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/GameOptions.js */ 50); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 8); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! decimal.js */ 24); +/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! decimal.js */ 20); @@ -59478,10 +58127,10 @@ function openImportFileHandler(evt) { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 48 */ +/* 44 */ /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ @@ -59510,7 +58159,7 @@ module.exports = g; /***/ }), -/* 49 */ +/* 45 */ /*!***********************************************!*\ !*** ./node_modules/pako/lib/utils/common.js ***! \***********************************************/ @@ -59625,7 +58274,7 @@ exports.setTyped(TYPED_OK); /***/ }), -/* 50 */ +/* 46 */ /*!*******************************************!*\ !*** ./node_modules/jszip/lib/support.js ***! \*******************************************/ @@ -59666,15 +58315,15 @@ else { } try { - exports.nodestream = !!__webpack_require__(/*! readable-stream */ 112).Readable; + exports.nodestream = !!__webpack_require__(/*! readable-stream */ 110).Readable; } catch(e) { exports.nodestream = false; } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 61).Buffer)) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 56).Buffer)) /***/ }), -/* 51 */ +/* 47 */ /*!*************************!*\ !*** ./utils/LogBox.js ***! \*************************/ @@ -59686,7 +58335,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logBoxUpdateText", function() { return logBoxUpdateText; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logBoxOpened", function() { return logBoxOpened; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logBoxCurrentScript", function() { return logBoxCurrentScript; }); -/* harmony import */ var _src_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/NetscriptWorker.js */ 21); +/* harmony import */ var _src_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/NetscriptWorker.js */ 22); /* harmony import */ var _HelperFunctions_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./HelperFunctions.js */ 1); @@ -59756,10 +58405,10 @@ function logBoxUpdateText() { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 52 */ +/* 48 */ /*!************************************************************!*\ !*** ./node_modules/readable-stream/lib/_stream_duplex.js ***! \************************************************************/ @@ -59796,7 +58445,7 @@ function logBoxUpdateText() { /**/ -var processNextTick = __webpack_require__(/*! process-nextick-args */ 67).nextTick; +var processNextTick = __webpack_require__(/*! process-nextick-args */ 64).nextTick; /**/ /**/ @@ -59811,12 +58460,12 @@ var objectKeys = Object.keys || function (obj) { module.exports = Duplex; /**/ -var util = __webpack_require__(/*! core-util-is */ 59); -util.inherits = __webpack_require__(/*! inherits */ 55); +var util = __webpack_require__(/*! core-util-is */ 55); +util.inherits = __webpack_require__(/*! inherits */ 51); /**/ -var Readable = __webpack_require__(/*! ./_stream_readable */ 111); -var Writable = __webpack_require__(/*! ./_stream_writable */ 80); +var Readable = __webpack_require__(/*! ./_stream_readable */ 109); +var Writable = __webpack_require__(/*! ./_stream_writable */ 76); util.inherits(Duplex, Readable); @@ -59892,7 +58541,7 @@ function forEach(xs, f) { } /***/ }), -/* 53 */ +/* 49 */ /*!***************************!*\ !*** ./src/Literature.js ***! \***************************/ @@ -59903,7 +58552,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Literatures", function() { return Literatures; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initLiterature", function() { return initLiterature; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "showLiterature", function() { return showLiterature; }); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* Literature.js @@ -60338,7 +58987,7 @@ function initLiterature() { /***/ }), -/* 54 */ +/* 50 */ /*!******************************!*\ !*** ./utils/GameOptions.js ***! \******************************/ @@ -60394,10 +59043,10 @@ function gameOptionsBoxOpen() { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 55 */ +/* 51 */ /*!***************************************************!*\ !*** ./node_modules/inherits/inherits_browser.js ***! \***************************************************/ @@ -60429,7 +59078,7 @@ if (typeof Object.create === 'function') { /***/ }), -/* 56 */ +/* 52 */ /*!****************************************!*\ !*** ./node_modules/jszip/lib/utf8.js ***! \****************************************/ @@ -60438,10 +59087,10 @@ if (typeof Object.create === 'function') { "use strict"; -var utils = __webpack_require__(/*! ./utils */ 32); -var support = __webpack_require__(/*! ./support */ 50); -var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 65); -var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 38); +var utils = __webpack_require__(/*! ./utils */ 28); +var support = __webpack_require__(/*! ./support */ 46); +var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62); +var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 34); /** * The following functions come from pako, from pako/lib/utils/strings @@ -60714,7 +59363,7 @@ exports.Utf8EncodeWorker = Utf8EncodeWorker; /***/ }), -/* 57 */ +/* 53 */ /*!*************************!*\ !*** ./src/Prestige.js ***! \*************************/ @@ -60724,28 +59373,28 @@ exports.Utf8EncodeWorker = Utf8EncodeWorker; __webpack_require__.r(__webpack_exports__); /* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeAugmentation", function() { return prestigeAugmentation; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prestigeSourceFile", function() { return prestigeSourceFile; }); -/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 41); -/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations.js */ 19); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 15); -/* harmony import */ var _CinematicText_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CinematicText.js */ 70); -/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Company.js */ 9); -/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CreateProgram.js */ 14); +/* harmony import */ var _ActiveScriptsUI_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ActiveScriptsUI.js */ 42); +/* harmony import */ var _Augmentations_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Augmentations.js */ 18); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 12); +/* harmony import */ var _CinematicText_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./CinematicText.js */ 66); +/* harmony import */ var _Company_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Company.js */ 8); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CreateProgram.js */ 17); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./engine.js */ 5); -/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Faction.js */ 11); -/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Gang.js */ 37); +/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Faction.js */ 9); +/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Gang.js */ 33); /* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Location.js */ 4); -/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Message.js */ 29); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./NetscriptWorker.js */ 21); +/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Message.js */ 27); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SpecialServerIps.js */ 17); -/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./StockMarket.js */ 22); -/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Terminal.js */ 18); -/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! decimal.js */ 24); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./StockMarket.js */ 29); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! decimal.js */ 20); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -61056,10 +59705,10 @@ function prestigeSourceFile() { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 39))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 35))) /***/ }), -/* 58 */ +/* 54 */ /*!********************************************!*\ !*** ./node_modules/jszip/lib/external.js ***! \********************************************/ @@ -61076,7 +59725,7 @@ var ES6Promise = null; if (typeof Promise !== "undefined") { ES6Promise = Promise; } else { - ES6Promise = __webpack_require__(/*! lie */ 153); + ES6Promise = __webpack_require__(/*! lie */ 152); } /** @@ -61088,7 +59737,7 @@ module.exports = { /***/ }), -/* 59 */ +/* 55 */ /*!***********************************************!*\ !*** ./node_modules/core-util-is/lib/util.js ***! \***********************************************/ @@ -61202,203 +59851,10 @@ function objectToString(o) { return Object.prototype.toString.call(o); } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 61).Buffer)) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 56).Buffer)) /***/ }), -/* 60 */ -/*!*****************************************!*\ - !*** ./node_modules/process/browser.js ***! - \*****************************************/ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 61 */ +/* 56 */ /*!**************************************!*\ !*** ./node_modules/buffer/index.js ***! \**************************************/ @@ -61415,9 +59871,9 @@ process.umask = function() { return 0; }; -var base64 = __webpack_require__(/*! base64-js */ 180) -var ieee754 = __webpack_require__(/*! ieee754 */ 179) -var isArray = __webpack_require__(/*! isarray */ 113) +var base64 = __webpack_require__(/*! base64-js */ 178) +var ieee754 = __webpack_require__(/*! ieee754 */ 177) +var isArray = __webpack_require__(/*! isarray */ 111) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -63195,11 +61651,310 @@ function isnan (val) { return val !== val // eslint-disable-line no-self-compare } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ 48))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ 44))) /***/ }), -/* 62 */, -/* 63 */ +/* 57 */ +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 58 */ +/*!*************************!*\ + !*** ./src/TextFile.js ***! + \*************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextFile", function() { return TextFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTextFile", function() { return getTextFile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createTextFile", function() { return createTextFile; }); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/JSONReviver.js */ 7); + + + + +function TextFile(fn="", txt="") { + this.fn = fn.endsWith(".txt") ? fn : fn + ".txt"; + this.fn = this.fn.replace(/\s+/g, ''); + this.text = String(txt); +} + +TextFile.prototype.append = function(txt) { + this.text += String(txt); +} + +TextFile.prototype.write = function(txt) { + this.text = String(txt); +} + +TextFile.prototype.read = function() { + return this.txt; +} + +TextFile.prototype.show = function() { + Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])(this.fn + "

" + this.text, true); +} + +TextFile.prototype.download = function() { + var filename = this.fn; + var file = new Blob([this.text], {type: 'text/plain'}); + if (window.navigator.msSaveOrOpenBlob) {// IE10+ + window.navigator.msSaveOrOpenBlob(file, filename); + } else { // Others + var a = document.createElement("a"), + url = URL.createObjectURL(file); + a.href = url; + a.download = this.fn; + document.body.appendChild(a); + a.click(); + setTimeout(function() { + document.body.removeChild(a); + window.URL.revokeObjectURL(url); + }, 0); + } +} + +TextFile.prototype.toJSON = function() { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Generic_toJSON"])("TextFile", this); +} + +TextFile.fromJSON = function(value) { + return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Generic_fromJSON"])(TextFile, value.data); +} + +_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_2__["Reviver"].constructors.TextFile = TextFile; + +function getTextFile(fn, server) { + if (!fn.endsWith(".txt")) {fn += ".txt";} + for (var i = 0; i < server.textFiles.length; ++i) { + if (server.textFiles[i].fn === fn) { + return server.textFiles[i]; + } + } + return null; +} + +//Returns the TextFile object that was just created +function createTextFile(fn, txt, server) { + if (getTextFile(fn, server) !== null) { + console.log("ERROR: createTextFile failed because the specified " + + "server already has a text file with the same fn"); + return; + } + var file = new TextFile(fn, txt); + server.textFiles.push(file); + return file; +} + +function deleteTextFile(fn, server) { + if (!fn.endsWith(".txt")) {fn += ".txt";} + for (var i = 0; i < server.textFiles.length; ++i) { + if (server.textFiles[i].fn === fn) { + server.textFiles.splice(i, 1); + return true; + } + } + return false; +} + + + + +/***/ }), +/* 59 */, +/* 60 */ /*!*************************************!*\ !*** ./src/NetscriptJSEvaluator.js ***! \*************************************/ @@ -63210,7 +61965,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeScriptBlob", function() { return makeScriptBlob; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeJSScript", function() { return executeJSScript; }); /* harmony import */ var _NetscriptJSPreamble_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./NetscriptJSPreamble.js */ 128); -/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 6); +/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31); @@ -63323,7 +62078,7 @@ function _getScriptUrls(script, scripts, seen) { /***/ }), -/* 64 */ +/* 61 */ /*!****************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_global.js ***! \****************************************************************************/ @@ -63335,7 +62090,7 @@ var global = module.exports = typeof window != 'undefined' && window.Math == Mat if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }), -/* 65 */ +/* 62 */ /*!***********************************************!*\ !*** ./node_modules/jszip/lib/nodejsUtils.js ***! \***********************************************/ @@ -63395,17 +62150,17 @@ module.exports = { } }; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 61).Buffer)) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ 56).Buffer)) /***/ }), -/* 66 */ +/* 63 */ /*!*******************************************!*\ !*** ./node_modules/safe-buffer/index.js ***! \*******************************************/ /***/ (function(module, exports, __webpack_require__) { /* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(/*! buffer */ 61) +var buffer = __webpack_require__(/*! buffer */ 56) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers @@ -63469,7 +62224,7 @@ SafeBuffer.allocUnsafeSlow = function (size) { /***/ }), -/* 67 */ +/* 64 */ /*!****************************************************!*\ !*** ./node_modules/process-nextick-args/index.js ***! \****************************************************/ @@ -63521,349 +62276,74 @@ function nextTick(fn, arg1, arg2, arg3) { } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ 60))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../process/browser.js */ 57))) /***/ }), -/* 68 */ -/*!************************************************!*\ - !*** ./node_modules/sprintf-js/src/sprintf.js ***! - \************************************************/ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */ - -!function() { - 'use strict' - - var re = { - not_string: /[^s]/, - not_bool: /[^t]/, - not_type: /[^T]/, - not_primitive: /[^v]/, - number: /[diefg]/, - numeric_arg: /[bcdiefguxX]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[\+\-]/ - } - - function sprintf(key) { - // `arguments` is not an array, but should be fine for this call - return sprintf_format(sprintf_parse(key), arguments) - } - - function vsprintf(fmt, argv) { - return sprintf.apply(null, [fmt].concat(argv || [])) - } - - function sprintf_format(parse_tree, argv) { - var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign - for (i = 0; i < tree_length; i++) { - if (typeof parse_tree[i] === 'string') { - output += parse_tree[i] - } - else if (Array.isArray(parse_tree[i])) { - match = parse_tree[i] // convenience purposes only - if (match[2]) { // keyword argument - arg = argv[cursor] - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])) - } - arg = arg[match[2][k]] - } - } - else if (match[1]) { // positional argument (explicit) - arg = argv[match[1]] - } - else { // positional argument (implicit) - arg = argv[cursor++] - } - - if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) { - arg = arg() - } - - if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) { - throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) - } - - if (re.number.test(match[8])) { - is_positive = arg >= 0 - } - - switch (match[8]) { - case 'b': - arg = parseInt(arg, 10).toString(2) - break - case 'c': - arg = String.fromCharCode(parseInt(arg, 10)) - break - case 'd': - case 'i': - arg = parseInt(arg, 10) - break - case 'j': - arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) - break - case 'e': - arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential() - break - case 'f': - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) - break - case 'g': - arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg) - break - case 'o': - arg = (parseInt(arg, 10) >>> 0).toString(8) - break - case 's': - arg = String(arg) - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 't': - arg = String(!!arg) - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'T': - arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'u': - arg = parseInt(arg, 10) >>> 0 - break - case 'v': - arg = arg.valueOf() - arg = (match[7] ? arg.substring(0, match[7]) : arg) - break - case 'x': - arg = (parseInt(arg, 10) >>> 0).toString(16) - break - case 'X': - arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() - break - } - if (re.json.test(match[8])) { - output += arg - } - else { - if (re.number.test(match[8]) && (!is_positive || match[3])) { - sign = is_positive ? '+' : '-' - arg = arg.toString().replace(re.sign, '') - } - else { - sign = '' - } - pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' ' - pad_length = match[6] - (sign + arg).length - pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' - output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) - } - } - } - return output - } - - var sprintf_cache = Object.create(null) - - function sprintf_parse(fmt) { - if (sprintf_cache[fmt]) { - return sprintf_cache[fmt] - } - - var _fmt = fmt, match, parse_tree = [], arg_names = 0 - while (_fmt) { - if ((match = re.text.exec(_fmt)) !== null) { - parse_tree.push(match[0]) - } - else if ((match = re.modulo.exec(_fmt)) !== null) { - parse_tree.push('%') - } - else if ((match = re.placeholder.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1 - var field_list = [], replacement_field = match[2], field_match = [] - if ((field_match = re.key.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = re.key_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else if ((field_match = re.index_access.exec(replacement_field)) !== null) { - field_list.push(field_match[1]) - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - } - } - else { - throw new SyntaxError('[sprintf] failed to parse named argument key') - } - match[2] = field_list - } - else { - arg_names |= 2 - } - if (arg_names === 3) { - throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') - } - parse_tree.push(match) - } - else { - throw new SyntaxError('[sprintf] unexpected placeholder') - } - _fmt = _fmt.substring(match[0].length) - } - return sprintf_cache[fmt] = parse_tree - } - - /** - * export to either browser or node.js - */ - /* eslint-disable quote-props */ - if (true) { - exports['sprintf'] = sprintf - exports['vsprintf'] = vsprintf - } - if (typeof window !== 'undefined') { - window['sprintf'] = sprintf - window['vsprintf'] = vsprintf - - if (true) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return { - 'sprintf': sprintf, - 'vsprintf': vsprintf - } - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) - } - } - /* eslint-enable quote-props */ -}() - - -/***/ }), -/* 69 */ -/*!*************************************!*\ - !*** ./src/NetscriptEnvironment.js ***! - \*************************************/ +/* 65 */ +/*!******************************!*\ + !*** ./src/NetscriptPort.js ***! + \******************************/ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Environment", function() { return Environment; }); -/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HacknetNode.js */ 40); -/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 31); -/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptPort.js */ 46); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NetscriptPort", function() { return NetscriptPort; }); +/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Settings.js */ 19); - - -/* Environment - * NetScript program environment - */ -function Environment(workerScript,parent) { - if (parent){ - //Create a copy of parent's variables - //this.vars = parent.vars; - this.vars = Object.assign({}, parent.vars); - } else { - this.vars = Object(_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_1__["NetscriptFunctions"])(workerScript); - } - this.parent = parent; - this.stopFlag = false; +function NetscriptPort() { + this.data = []; } -Environment.prototype = { - //Create a "subscope", which is a new new "sub-environment" - //The subscope is linked to this through its parent variable - extend: function() { - return new Environment(null, this); - }, - //Finds the scope where the variable with the given name is defined - lookup: function(name) { - var scope = this; - while (scope) { - if (Object.prototype.hasOwnProperty.call(scope.vars, name)) { - return scope; - } - scope = scope.parent; - } - return null; - }, - - //Get the current value of a variable - get: function(name) { - if (name in this.vars) { - return this.vars[name]; - } - throw new Error("Undefined variable " + name); - }, - - //Sets the value of a variable in any scope - set: function(name, value) { - var scope = this.lookup(name); - - //If scope has a value, then this variable is already set in a higher scope, so - //set is there. Otherwise, create a new variable in the local scope - if (scope !== null) { - return scope.vars[name] = value; - } else { - return this.vars[name] = value; - } - }, - - setArrayElement: function(name, idx, value) { - if (!(idx instanceof Array)) { - throw new Error("idx parameter is not an Array"); - } - var scope = this.lookup(name); - if (!scope && this.parent) { - throw new Error("Undefined variable " + name); - } - var arr = (scope || this).vars[name]; - if (!(arr.constructor === Array || arr instanceof Array)) { - throw new Error("Variable is not an array: " + name); - } - var res = arr; - for (var iterator = 0; iterator < idx.length-1; ++iterator) { - var i = idx[iterator]; - if (!(res instanceof Array) || i >= res.length) { - throw new Error("Out-of-bounds array access"); - } - res = res[i]; - } - - //Cant assign to ports or HacknetNodes - if (res[idx[idx.length-1]] instanceof _HacknetNode_js__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"]) { - throw new Error("Cannot assign a Hacknet Node handle to a new value"); - } - if (res[idx[idx.length-1]] instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_2__["NetscriptPort"]) { - throw new Error("Cannot assign a Netscript Port handle to a new value"); - } - return res[idx[idx.length-1]] = value; - }, - - //Creates (or overwrites) a variable in the current scope - def: function(name, value) { - return this.vars[name] = value; +NetscriptPort.prototype.write = function(data) { + this.data.push(data); + if (this.data.length > _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) { + return this.data.shift(); } -}; + return null; +} + +NetscriptPort.prototype.tryWrite = function(data) { + if (this.data.length >= _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity) { + return false; + } + this.data.push(data); + return true; +} + +NetscriptPort.prototype.read = function() { + if (this.data.length === 0) { + return "NULL PORT DATA"; + } + return this.data.shift(); +} + +NetscriptPort.prototype.peek = function() { + if (this.data.length === 0) { + return "NULL PORT DATA"; + } else { + var foo = this.data.slice(); + return foo[0]; + } +} + +NetscriptPort.prototype.full = function() { + return this.data.length == _Settings_js__WEBPACK_IMPORTED_MODULE_0__["Settings"].MaxPortCapacity; +} + +NetscriptPort.prototype.empty = function() { + return this.data.length === 0; +} + +NetscriptPort.prototype.clear = function() { + this.data.length = 0; +} /***/ }), -/* 70 */ +/* 66 */ /*!******************************!*\ !*** ./src/CinematicText.js ***! \******************************/ @@ -63976,7 +62456,7 @@ function cinematicTextEnd() { /***/ }), -/* 71 */ +/* 67 */ /*!*************************!*\ !*** ./src/HelpText.js ***! \*************************/ @@ -64206,10 +62686,10 @@ let HelpTexts = { /***/ }), -/* 72 */, -/* 73 */, -/* 74 */, -/* 75 */ +/* 68 */, +/* 69 */, +/* 70 */, +/* 71 */ /*!************************************************!*\ !*** ./node_modules/pako/lib/zlib/messages.js ***! \************************************************/ @@ -64251,7 +62731,7 @@ module.exports = { /***/ }), -/* 76 */ +/* 72 */ /*!*****************************************!*\ !*** ./node_modules/jszip/lib/crc32.js ***! \*****************************************/ @@ -64260,7 +62740,7 @@ module.exports = { "use strict"; -var utils = __webpack_require__(/*! ./utils */ 32); +var utils = __webpack_require__(/*! ./utils */ 28); /** * The following functions come from pako, from pako/lib/zlib/crc32.js @@ -64338,7 +62818,7 @@ module.exports = function crc32wrapper(input, crc) { /***/ }), -/* 77 */ +/* 73 */ /*!****************************************************!*\ !*** ./node_modules/jszip/lib/compressedObject.js ***! \****************************************************/ @@ -64347,11 +62827,11 @@ module.exports = function crc32wrapper(input, crc) { "use strict"; -var external = __webpack_require__(/*! ./external */ 58); -var DataWorker = __webpack_require__(/*! ./stream/DataWorker */ 98); -var DataLengthProbe = __webpack_require__(/*! ./stream/DataLengthProbe */ 97); -var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 96); -var DataLengthProbe = __webpack_require__(/*! ./stream/DataLengthProbe */ 97); +var external = __webpack_require__(/*! ./external */ 54); +var DataWorker = __webpack_require__(/*! ./stream/DataWorker */ 97); +var DataLengthProbe = __webpack_require__(/*! ./stream/DataLengthProbe */ 96); +var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 95); +var DataLengthProbe = __webpack_require__(/*! ./stream/DataLengthProbe */ 96); /** * Represent a compressed object, with everything needed to decompress it. @@ -64423,19 +62903,19 @@ module.exports = CompressedObject; /***/ }), -/* 78 */ +/* 74 */ /*!*********************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_descriptors.js ***! \*********************************************************************************/ /***/ (function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(/*! ./_fails */ 102)(function(){ +module.exports = !__webpack_require__(/*! ./_fails */ 101)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }), -/* 79 */ +/* 75 */ /*!*******************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_is-object.js ***! \*******************************************************************************/ @@ -64446,7 +62926,7 @@ module.exports = function(it){ }; /***/ }), -/* 80 */ +/* 76 */ /*!**************************************************************!*\ !*** ./node_modules/readable-stream/lib/_stream_writable.js ***! \**************************************************************/ @@ -64482,7 +62962,7 @@ module.exports = function(it){ /**/ -var processNextTick = __webpack_require__(/*! process-nextick-args */ 67).nextTick; +var processNextTick = __webpack_require__(/*! process-nextick-args */ 64).nextTick; /**/ module.exports = Writable; @@ -64519,23 +62999,23 @@ var Duplex; Writable.WritableState = WritableState; /**/ -var util = __webpack_require__(/*! core-util-is */ 59); -util.inherits = __webpack_require__(/*! inherits */ 55); +var util = __webpack_require__(/*! core-util-is */ 55); +util.inherits = __webpack_require__(/*! inherits */ 51); /**/ /**/ var internalUtil = { - deprecate: __webpack_require__(/*! util-deprecate */ 173) + deprecate: __webpack_require__(/*! util-deprecate */ 172) }; /**/ /**/ -var Stream = __webpack_require__(/*! ./internal/streams/stream */ 110); +var Stream = __webpack_require__(/*! ./internal/streams/stream */ 108); /**/ /**/ -var Buffer = __webpack_require__(/*! safe-buffer */ 66).Buffer; +var Buffer = __webpack_require__(/*! safe-buffer */ 63).Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -64546,14 +63026,14 @@ function _isUint8Array(obj) { /**/ -var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ 109); +var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ 107); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 52); + Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 48); options = options || {}; @@ -64703,7 +63183,7 @@ if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.protot } function Writable(options) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 52); + Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 48); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` @@ -65130,26 +63610,26 @@ Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ 60), __webpack_require__(/*! ./../../timers-browserify/main.js */ 108).setImmediate, __webpack_require__(/*! ./../../webpack/buildin/global.js */ 48))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ 57), __webpack_require__(/*! ./../../timers-browserify/main.js */ 112).setImmediate, __webpack_require__(/*! ./../../webpack/buildin/global.js */ 44))) /***/ }), -/* 81 */ +/* 77 */ /*!**********************************************************!*\ !*** ./node_modules/readable-stream/readable-browser.js ***! \**********************************************************/ /***/ (function(module, exports, __webpack_require__) { -exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ 111); +exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ 109); exports.Stream = exports; exports.Readable = exports; -exports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ 80); -exports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ 52); -exports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ 106); -exports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ 172); +exports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ 76); +exports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ 48); +exports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ 105); +exports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ 171); /***/ }), -/* 82 */ +/* 78 */ /*!***************************************!*\ !*** ./node_modules/events/events.js ***! \***************************************/ @@ -65460,7 +63940,7 @@ function isUndefined(arg) { /***/ }), -/* 83 */ +/* 79 */ /*!***************************************!*\ !*** (webpack)/buildin/amd-define.js ***! \***************************************/ @@ -65472,7 +63952,118 @@ module.exports = function() { /***/ }), -/* 84 */ +/* 80 */ +/*!*************************************!*\ + !*** ./src/NetscriptEnvironment.js ***! + \*************************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Environment", function() { return Environment; }); +/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./HacknetNode.js */ 38); +/* harmony import */ var _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NetscriptFunctions.js */ 26); +/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./NetscriptPort.js */ 65); + + + + +/* Environment + * NetScript program environment + */ +function Environment(workerScript,parent) { + if (parent){ + //Create a copy of parent's variables + //this.vars = parent.vars; + this.vars = Object.assign({}, parent.vars); + } else { + this.vars = Object(_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_1__["NetscriptFunctions"])(workerScript); + } + this.parent = parent; + this.stopFlag = false; +} +Environment.prototype = { + //Create a "subscope", which is a new new "sub-environment" + //The subscope is linked to this through its parent variable + extend: function() { + return new Environment(null, this); + }, + + //Finds the scope where the variable with the given name is defined + lookup: function(name) { + var scope = this; + while (scope) { + if (Object.prototype.hasOwnProperty.call(scope.vars, name)) { + return scope; + } + scope = scope.parent; + } + return null; + }, + + //Get the current value of a variable + get: function(name) { + if (name in this.vars) { + return this.vars[name]; + } + throw new Error("Undefined variable " + name); + }, + + //Sets the value of a variable in any scope + set: function(name, value) { + var scope = this.lookup(name); + + //If scope has a value, then this variable is already set in a higher scope, so + //set is there. Otherwise, create a new variable in the local scope + if (scope !== null) { + return scope.vars[name] = value; + } else { + return this.vars[name] = value; + } + }, + + setArrayElement: function(name, idx, value) { + if (!(idx instanceof Array)) { + throw new Error("idx parameter is not an Array"); + } + var scope = this.lookup(name); + if (!scope && this.parent) { + throw new Error("Undefined variable " + name); + } + var arr = (scope || this).vars[name]; + if (!(arr.constructor === Array || arr instanceof Array)) { + throw new Error("Variable is not an array: " + name); + } + var res = arr; + for (var iterator = 0; iterator < idx.length-1; ++iterator) { + var i = idx[iterator]; + if (!(res instanceof Array) || i >= res.length) { + throw new Error("Out-of-bounds array access"); + } + res = res[i]; + } + + //Cant assign to ports or HacknetNodes + if (res[idx[idx.length-1]] instanceof _HacknetNode_js__WEBPACK_IMPORTED_MODULE_0__["HacknetNode"]) { + throw new Error("Cannot assign a Hacknet Node handle to a new value"); + } + if (res[idx[idx.length-1]] instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_2__["NetscriptPort"]) { + throw new Error("Cannot assign a Netscript Port handle to a new value"); + } + return res[idx[idx.length-1]] = value; + }, + + //Creates (or overwrites) a variable in the current scope + def: function(name, value) { + return this.vars[name] = value; + } +}; + + + + +/***/ }), +/* 81 */ /*!********************************!*\ !*** ./src/ServerPurchases.js ***! \********************************/ @@ -65484,10 +64075,10 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "purchaseRamForHomeComputer", function() { return purchaseRamForHomeComputer; }); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server.js */ 10); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); -/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress.js */ 16); -/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12); +/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Server.js */ 14); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 11); @@ -65560,7 +64151,394 @@ function purchaseRamForHomeComputer(cost) { /***/ }), -/* 85 */ +/* 82 */ +/*!************************!*\ + !*** ./src/DarkWeb.js ***! + \************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkIfConnectedToDarkweb", function() { return checkIfConnectedToDarkweb; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeDarkwebTerminalCommand", function() { return executeDarkwebTerminalCommand; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "listAllDarkwebItems", function() { return listAllDarkwebItems; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buyDarkwebItem", function() { return buyDarkwebItem; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseDarkwebItemPrice", function() { return parseDarkwebItemPrice; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DarkWebItems", function() { return DarkWebItems; }); +/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CreateProgram.js */ 17); +/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Player.js */ 0); +/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16); +/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Terminal.js */ 15); +/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/IPAddress.js */ 13); +/* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); + + + + + + + + + +/* DarkWeb.js */ +//Posts a "help" message if connected to DarkWeb +function checkIfConnectedToDarkweb() { + if (_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"].hasOwnProperty("Darkweb Server")) { + var darkwebIp = _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_2__["SpecialServerIps"]["Darkweb Server"]; + if (!Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_4__["isValidIPAddress"])(darkwebIp)) {return;} + if (darkwebIp == _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getCurrentServer().ip) { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You are now connected to the dark web. From the dark web you can purchase illegal items. " + + "Use the 'buy -l' command to display a list of all the items you can buy. Use 'buy [item-name] " + + "to purchase an item"); + } + } + +} + +//Handler for dark web commands. The terminal's executeCommand() function will pass +//dark web-specific commands into this. It will pass in the raw split command array +//rather than the command string +function executeDarkwebTerminalCommand(commandArray) { + if (commandArray.length == 0) {return;} + switch (commandArray[0]) { + case "buy": + if (commandArray.length != 2) { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Incorrect number of arguments. Usage: "); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy -l"); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("buy [item name]"); + return; + } + var arg = commandArray[1]; + if (arg == "-l") { + listAllDarkwebItems(); + } else { + buyDarkwebItem(arg); + } + break; + default: + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Command not found"); + break; + } +} + +function listAllDarkwebItems() { + for (var item in DarkWebItems) { + if (DarkWebItems.hasOwnProperty(item)) { + var item = DarkWebItems[item]; + //Convert string using toLocaleString + var split = item.split(" - "); + if (split.length == 3 && split[1].charAt(0) == '$') { + split[1] = split[1].slice(1); + split[1] = split[1].replace(/,/g, ''); + var price = parseFloat(split[1]); + if (isNaN(price)) { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item); + return; + } + price = Object(_utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["formatNumber"])(price, 0); + split[1] = "$" + price.toString(); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(split.join(" - ")); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])(item); + } + } + } + + var priceString = split[1]; + //Check for errors + if (priceString.length == 0 || priceString.charAt(0) != '$') { + return -1; + } + //Remove dollar sign and commas + priceString = priceString.slice(1); + priceString = priceString.replace(/,/g, ''); + + //Convert string to numeric + var price = parseFloat(priceString); + if (isNaN(price)) {return -1;} + else {return price;} +} + +function buyDarkwebItem(itemName) { + if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.BruteSSHProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].BruteSSHProgram); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the BruteSSH.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.FTPCrackProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].FTPCrackProgram); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the FTPCrack.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.RelaySMTPProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].RelaySMTPProgram); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the relaySMTP.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.HTTPWormProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].HTTPWormProgram); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the HTTPWorm.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.SQLInjectProgram); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].SQLInjectProgram); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the SQLInject.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV1Program); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV1); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV1.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else if (itemName.toLowerCase() == _CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2.toLowerCase()) { + var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV2Program); + if (price > 0 && _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].money.gt(price)) { + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].loseMoney(price); + _Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_0__["Programs"].DeepscanV2); + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("You have purchased the DeepscanV2.exe program. The new program " + + "can be found on your home computer."); + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Not enough money to purchase " + itemName); + } + } else { + Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_3__["post"])("Unrecognized item"); + } +} + +function parseDarkwebItemPrice(itemDesc) { + var split = itemDesc.split(" - "); + if (split.length == 3) { + var priceString = split[1]; + //Check for errors + if (priceString.length == 0 || priceString.charAt(0) != '$') { + return -1; + } + //Remove dollar sign and commas + priceString = priceString.slice(1); + priceString = priceString.replace(/,/g, ''); + + //Convert string to numeric + var price = parseFloat(priceString); + if (isNaN(price)) {return -1;} + else {return price;} + } else { + return -1; + } +} + +let DarkWebItems = { + BruteSSHProgram: "BruteSSH.exe - $500,000 - Opens up SSH Ports", + FTPCrackProgram: "FTPCrack.exe - $1,500,000 - Opens up FTP Ports", + RelaySMTPProgram: "relaySMTP.exe - $5,000,000 - Opens up SMTP Ports", + HTTPWormProgram: "HTTPWorm.exe - $30,000,000 - Opens up HTTP Ports", + SQLInjectProgram: "SQLInject.exe - $250,000,000 - Opens up SQL Ports", + DeepScanV1Program: "DeepscanV1.exe - $500,000 - Enables 'scan-analyze' with a depth up to 5", + DeepScanV2Program: "DeepscanV2.exe - $25,000,000 - Enables 'scan-analyze' with a depth up to 10", +} + + + + +/***/ }), +/* 83 */ +/*!****************************!*\ + !*** ./src/FactionInfo.js ***! + \****************************/ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FactionInfos", function() { return FactionInfos; }); +//Contains the "information" property for all the Factions, which is just a description +//of each faction +function FactionInfo(infoText, enemies, offerHackingMission, offerHackingWork, offerFieldWork, offerSecurityWork) { + this.infoText = infoText; + this.enemies = enemies; + this.offerHackingMission = offerHackingMission; + this.offerHackingWork = offerHackingWork; + this.offerFieldWork = offerFieldWork; + this.offerSecurityWork = offerSecurityWork; + + // these are always all 1 for now. + this.augmentationPriceMult = 1; + this.augmentationRepRequirementMult = 1; +} + +const FactionInfos = { + //Endgame + "Illuminati": new FactionInfo("Humanity never changes. No matter how civilized society becomes, it will eventually fall back " + + "into chaos. And from this chaos, we are the Invisible hand that guides them to order. ", [], true, true, true, false), + + "Daedalus": new FactionInfo("Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.", [], true, true, true, false), + + "The Covenant": new FactionInfo("Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " + + "Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.

" + + "Only then can you discover immortality.", [], true, true, true, false), + + //Megacorporations, each forms its own faction + "ECorp": new FactionInfo("ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " + + "With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " + + "information universally accessible.", [], true, true, true, true), + + "MegaCorp": new FactionInfo("MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " + + "others have never even dreamed of. Our work fills the world's needs for food, water, power, and " + + "transporation on an unprecendented scale, in ways that no other company can.

" + + "In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.", [], true, true, true, true), + + "Bachman & Associates": new FactionInfo("Where Law and Business meet - thats where we are.

" + + "Legal Insight - Business Instinct - Experience Innovation", [], true, true, true, true), + + "Blade Industries": new FactionInfo("Augmentation is salvation", [], true, true, true, true), + + "NWO": new FactionInfo("The human being does not truly desire freedom. It wants " + + "to be observed, understood, and judged. It wants to be given purpose and " + + "direction in its life. That is why humans created God. " + + "And that is why humans created civilization - " + + "not because of willingness, " + + "but because of a need to be incorporated into higher orders of structure and meaning.", [], true, true, true, true), + + "Clarke Incorporated": new FactionInfo("Unlocking the power of the genome", [], true, true, true, true), + + "OmniTek Incorporated": new FactionInfo("Simply put, our mission is to design and build robots that make a difference", [], true, true, true, true), + + "Four Sigma": new FactionInfo("The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " + + "deep learning and innovative ideas. And improved by iteration. That's Four Sigma.", [], true, true, true, true), + + "KuaiGong International": new FactionInfo("Dream big. Work hard. Make history.", [], true, true, true, true), + + //Other Corporations + "Fulcrum Secret Technologies": new FactionInfo("The human organism has an innate desire to worship. " + + "That is why they created gods. If there were no gods, " + + "it would be necessary to create them. And now we can.", [], true, true, false, true), + + //Hacker groups + "BitRunners": new FactionInfo("Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+ + "It's all transformed into bits, stored in bits, communicated through bits. It’s impossible for any person " + + "to move, to live, to operate at any level without the use of bits. " + + "And when a person moves, lives, and operates, they leave behind their bits, mere traces of seemingly " + + "meaningless fragments of information. But these bits can be reconstructed. Transformed. Used.

" + + "Those who run the bits, run the world", [], true, true, false, false), + + + "The Black Hand": new FactionInfo("The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " + + "Technological power. " + + "And those at the top rule with an invisible hand. They built a society where the rich get richer, " + + "and everyone else suffers.

" + + "So much pain. So many lives. Their darkness must end.", [], true, true, true, false), + + "NiteSec": new FactionInfo( +" __..__
" + +" _.nITESECNIt.
" + +" .-'NITESECNITESEc.
" + +" .' NITESECNITESECn
" + +" / NITESECNITESEC;
" + +" : :NITESECNITESEC;
" + +" ; $ NITESECNITESECN
" + +" : _, ,N'ITESECNITESEC
" + +" : .+^^`, : `NITESECNIT
" + +" ) /), `-,-=,NITESECNI
" + +" / ^ ,-;|NITESECN;
" + +" / _.' '-';NITESECN
" + +" ( , ,-''`^NITE'
" + +" )` :`. .'
" + +" )-- ; `- /
" + +" \' _.-' :
" + +" ( _.-' \. \
" + +" \------. \ \
" + +" \. \ \
" + +" \ _.nIt
" + +" \ _.nITESECNi
" + +" nITESECNIT^' \
" + +" NITE^' ___ \
" + +" / .gP''''Tp. \
" + +" : d' . `b \
" + +" ; d' o `b ;
" + +" / d; `b|
" + +" /, $; @ `:
" + +" /' $$ ;
" + +" .' $$b o |
" + +" .' d$$$; :
" + +" / .d$$$$; , ;
" + +" d .dNITESEC $ |
" + +" :bp.__.gNITESEC$$ :$ ;
" + +" NITESECNITESECNIT $$b :
", [], true, true, false, false), + + //City factions, essentially governments + "Chongqing": new FactionInfo("Serve the people", ["Sector-12", "Aevum", "Volhaven"], true, true, true, true), + "Sector-12": new FactionInfo("The City of the Future", ["Chongqing", "New Tokyo", "Ishima", "Volhaven"], true, true, true, true), + "New Tokyo": new FactionInfo("Asia's World City", ["Sector-12", "Aevum", "Volhaven"], true, true, true, true), + "Aevum": new FactionInfo("The Silicon City", ["Chongqing", "New Tokyo", "Ishima", "Volhaven"], true, true, true, true), + "Ishima": new FactionInfo("The East Asian Order of the Future", ["Sector-12", "Aevum", "Volhaven"], true, true, true, true), + "Volhaven": new FactionInfo("Benefit, Honour, and Glory", ["Chongqing", "Sector-12", "New Tokyo", "Aevum", "Ishima"], true, true, true, true), + + //Criminal Organizations/Gangs + "Speakers for the Dead": new FactionInfo("It is better to reign in hell than to serve in heaven.", [], true, true, true, true), + + "The Dark Army": new FactionInfo("The World doesn't care about right or wrong. It's all about power.", [], true, true, true, false), + + "The Syndicate": new FactionInfo("Honor holds you back", [], true, true, true, true), + + "Silhouette": new FactionInfo("Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " + + "that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " + + "for.\n\n" + + "That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.", [], true, true, true, false), + + "Tetrads": new FactionInfo("Following the Mandate of Heaven and Carrying out the Way", [], false, false, true, true), + + "Slum Snakes": new FactionInfo("Slum Snakes rule!", [], false, false, true, true), + + //Earlygame factions - factions the player will prestige with early on that don't + //belong in other categories + "Netburners": new FactionInfo("~~//*>H4CK|\|3T 8URN3R5**>?>\\~~", [], true, true, false, false), + + "Tian Di Hui": new FactionInfo("Obey Heaven and Work Righteousness", [], true, true, false, true), + + "CyberSec": new FactionInfo("The Internet is the first thing that humanity has built that humanity doesn’t understand, " + + "the largest experiment in anarchy that we have ever had. And as the world becomes increasingly " + + "dominated by the internet, society approaches the brink of total chaos. " + + "We serve only to protect society, to protect humanity, to protect the world from its imminent collapse.", [], true, true, false, false), + + //Special Factions + "Bladeburners": new FactionInfo("It's too bad they won't live. But then again, who does?

" + + "Note that for this faction, reputation can only be gained through Bladeburner actions. Completing " + + "Bladeburner contracts/operations will increase your reputation.", [], false, false, false, false), +} + + + + +/***/ }), +/* 84 */ /*!***********************************************************!*\ !*** ./node_modules/jszip/lib/reader/Uint8ArrayReader.js ***! \***********************************************************/ @@ -65568,8 +64546,8 @@ function purchaseRamForHomeComputer(cost) { "use strict"; -var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 87); -var utils = __webpack_require__(/*! ../utils */ 32); +var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 86); +var utils = __webpack_require__(/*! ../utils */ 28); function Uint8ArrayReader(data) { ArrayReader.call(this, data); @@ -65592,7 +64570,7 @@ module.exports = Uint8ArrayReader; /***/ }), -/* 86 */ +/* 85 */ /*!*****************************************************!*\ !*** ./node_modules/jszip/lib/reader/DataReader.js ***! \*****************************************************/ @@ -65600,7 +64578,7 @@ module.exports = Uint8ArrayReader; "use strict"; -var utils = __webpack_require__(/*! ../utils */ 32); +var utils = __webpack_require__(/*! ../utils */ 28); function DataReader(data) { this.data = data; // type : see implementation @@ -65718,7 +64696,7 @@ module.exports = DataReader; /***/ }), -/* 87 */ +/* 86 */ /*!******************************************************!*\ !*** ./node_modules/jszip/lib/reader/ArrayReader.js ***! \******************************************************/ @@ -65726,8 +64704,8 @@ module.exports = DataReader; "use strict"; -var DataReader = __webpack_require__(/*! ./DataReader */ 86); -var utils = __webpack_require__(/*! ../utils */ 32); +var DataReader = __webpack_require__(/*! ./DataReader */ 85); +var utils = __webpack_require__(/*! ../utils */ 28); function ArrayReader(data) { DataReader.call(this, data); @@ -65785,7 +64763,7 @@ module.exports = ArrayReader; /***/ }), -/* 88 */ +/* 87 */ /*!****************************************************!*\ !*** ./node_modules/jszip/lib/reader/readerFor.js ***! \****************************************************/ @@ -65794,12 +64772,12 @@ module.exports = ArrayReader; "use strict"; -var utils = __webpack_require__(/*! ../utils */ 32); -var support = __webpack_require__(/*! ../support */ 50); -var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 87); -var StringReader = __webpack_require__(/*! ./StringReader */ 133); -var NodeBufferReader = __webpack_require__(/*! ./NodeBufferReader */ 132); -var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 85); +var utils = __webpack_require__(/*! ../utils */ 28); +var support = __webpack_require__(/*! ../support */ 46); +var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 86); +var StringReader = __webpack_require__(/*! ./StringReader */ 132); +var NodeBufferReader = __webpack_require__(/*! ./NodeBufferReader */ 131); +var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 84); /** * Create a reader adapted to the data. @@ -65823,7 +64801,7 @@ module.exports = function (data) { /***/ }), -/* 89 */ +/* 88 */ /*!*********************************************!*\ !*** ./node_modules/jszip/lib/signature.js ***! \*********************************************/ @@ -65840,7 +64818,7 @@ exports.DATA_DESCRIPTOR = "PK\x07\x08"; /***/ }), -/* 90 */ +/* 89 */ /*!*************************************************!*\ !*** ./node_modules/pako/lib/zlib/constants.js ***! \*************************************************/ @@ -65918,7 +64896,7 @@ module.exports = { /***/ }), -/* 91 */ +/* 90 */ /*!***********************************************!*\ !*** ./node_modules/pako/lib/zlib/zstream.js ***! \***********************************************/ @@ -65975,7 +64953,7 @@ module.exports = ZStream; /***/ }), -/* 92 */ +/* 91 */ /*!************************************************!*\ !*** ./node_modules/pako/lib/utils/strings.js ***! \************************************************/ @@ -65986,7 +64964,7 @@ module.exports = ZStream; -var utils = __webpack_require__(/*! ./common */ 49); +var utils = __webpack_require__(/*! ./common */ 45); // Quick check if we can use fast array to bin string conversion @@ -66170,7 +65148,7 @@ exports.utf8border = function (buf, max) { /***/ }), -/* 93 */ +/* 92 */ /*!*********************************************!*\ !*** ./node_modules/pako/lib/zlib/crc32.js ***! \*********************************************/ @@ -66239,7 +65217,7 @@ module.exports = crc32; /***/ }), -/* 94 */ +/* 93 */ /*!***********************************************!*\ !*** ./node_modules/pako/lib/zlib/adler32.js ***! \***********************************************/ @@ -66300,7 +65278,7 @@ module.exports = adler32; /***/ }), -/* 95 */ +/* 94 */ /*!************************************************!*\ !*** ./node_modules/jszip/lib/compressions.js ***! \************************************************/ @@ -66309,7 +65287,7 @@ module.exports = adler32; "use strict"; -var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 38); +var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 34); exports.STORE = { magic: "\x00\x00", @@ -66320,11 +65298,11 @@ exports.STORE = { return new GenericWorker("STORE decompression"); } }; -exports.DEFLATE = __webpack_require__(/*! ./flate */ 147); +exports.DEFLATE = __webpack_require__(/*! ./flate */ 146); /***/ }), -/* 96 */ +/* 95 */ /*!*****************************************************!*\ !*** ./node_modules/jszip/lib/stream/Crc32Probe.js ***! \*****************************************************/ @@ -66333,9 +65311,9 @@ exports.DEFLATE = __webpack_require__(/*! ./flate */ 147); "use strict"; -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 38); -var crc32 = __webpack_require__(/*! ../crc32 */ 76); -var utils = __webpack_require__(/*! ../utils */ 32); +var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 34); +var crc32 = __webpack_require__(/*! ../crc32 */ 72); +var utils = __webpack_require__(/*! ../utils */ 28); /** * A worker which calculate the crc32 of the data flowing through. @@ -66358,7 +65336,7 @@ module.exports = Crc32Probe; /***/ }), -/* 97 */ +/* 96 */ /*!**********************************************************!*\ !*** ./node_modules/jszip/lib/stream/DataLengthProbe.js ***! \**********************************************************/ @@ -66367,8 +65345,8 @@ module.exports = Crc32Probe; "use strict"; -var utils = __webpack_require__(/*! ../utils */ 32); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 38); +var utils = __webpack_require__(/*! ../utils */ 28); +var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 34); /** * A worker which calculate the total length of the data flowing through. @@ -66397,7 +65375,7 @@ module.exports = DataLengthProbe; /***/ }), -/* 98 */ +/* 97 */ /*!*****************************************************!*\ !*** ./node_modules/jszip/lib/stream/DataWorker.js ***! \*****************************************************/ @@ -66406,8 +65384,8 @@ module.exports = DataLengthProbe; "use strict"; -var utils = __webpack_require__(/*! ../utils */ 32); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 38); +var utils = __webpack_require__(/*! ../utils */ 28); +var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 34); // the size of the generated chunks // TODO expose this as a public variable @@ -66523,7 +65501,7 @@ module.exports = DataWorker; /***/ }), -/* 99 */ +/* 98 */ /*!********************************************!*\ !*** ./node_modules/jszip/lib/defaults.js ***! \********************************************/ @@ -66544,7 +65522,7 @@ exports.dosPermissions = null; /***/ }), -/* 100 */ +/* 99 */ /*!*******************************************************!*\ !*** ./node_modules/jszip/lib/stream/StreamHelper.js ***! \*******************************************************/ @@ -66553,17 +65531,17 @@ exports.dosPermissions = null; "use strict"; /* WEBPACK VAR INJECTION */(function(Buffer) { -var utils = __webpack_require__(/*! ../utils */ 32); -var ConvertWorker = __webpack_require__(/*! ./ConvertWorker */ 151); -var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 38); -var base64 = __webpack_require__(/*! ../base64 */ 105); -var support = __webpack_require__(/*! ../support */ 50); -var external = __webpack_require__(/*! ../external */ 58); +var utils = __webpack_require__(/*! ../utils */ 28); +var ConvertWorker = __webpack_require__(/*! ./ConvertWorker */ 150); +var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 34); +var base64 = __webpack_require__(/*! ../base64 */ 104); +var support = __webpack_require__(/*! ../support */ 46); +var external = __webpack_require__(/*! ../external */ 54); var NodejsStreamOutputAdapter = null; if (support.nodestream) { try { - NodejsStreamOutputAdapter = __webpack_require__(/*! ../nodejs/NodejsStreamOutputAdapter */ 150); + NodejsStreamOutputAdapter = __webpack_require__(/*! ../nodejs/NodejsStreamOutputAdapter */ 149); } catch(e) {} } @@ -66764,17 +65742,17 @@ StreamHelper.prototype = { module.exports = StreamHelper; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ 61).Buffer)) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ 56).Buffer)) /***/ }), -/* 101 */ +/* 100 */ /*!********************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_dom-create.js ***! \********************************************************************************/ /***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(/*! ./_is-object */ 79) - , document = __webpack_require__(/*! ./_global */ 64).document +var isObject = __webpack_require__(/*! ./_is-object */ 75) + , document = __webpack_require__(/*! ./_global */ 61).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ @@ -66782,7 +65760,7 @@ module.exports = function(it){ }; /***/ }), -/* 102 */ +/* 101 */ /*!***************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_fails.js ***! \***************************************************************************/ @@ -66797,14 +65775,14 @@ module.exports = function(exec){ }; /***/ }), -/* 103 */ +/* 102 */ /*!*************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_ctx.js ***! \*************************************************************************/ /***/ (function(module, exports, __webpack_require__) { // optional / simple context binding -var aFunction = __webpack_require__(/*! ./_a-function */ 164); +var aFunction = __webpack_require__(/*! ./_a-function */ 163); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; @@ -66825,7 +65803,7 @@ module.exports = function(fn, that, length){ }; /***/ }), -/* 104 */ +/* 103 */ /*!**************************************************************************!*\ !*** ./node_modules/jszip/node_modules/core-js/library/modules/_core.js ***! \**************************************************************************/ @@ -66835,7 +65813,7 @@ var core = module.exports = {version: '2.3.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }), -/* 105 */ +/* 104 */ /*!******************************************!*\ !*** ./node_modules/jszip/lib/base64.js ***! \******************************************/ @@ -66843,8 +65821,8 @@ if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef "use strict"; -var utils = __webpack_require__(/*! ./utils */ 32); -var support = __webpack_require__(/*! ./support */ 50); +var utils = __webpack_require__(/*! ./utils */ 28); +var support = __webpack_require__(/*! ./support */ 46); // private property var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; @@ -66951,7 +65929,7 @@ exports.decode = function(input) { /***/ }), -/* 106 */ +/* 105 */ /*!***************************************************************!*\ !*** ./node_modules/readable-stream/lib/_stream_transform.js ***! \***************************************************************/ @@ -67025,11 +66003,11 @@ exports.decode = function(input) { module.exports = Transform; -var Duplex = __webpack_require__(/*! ./_stream_duplex */ 52); +var Duplex = __webpack_require__(/*! ./_stream_duplex */ 48); /**/ -var util = __webpack_require__(/*! core-util-is */ 59); -util.inherits = __webpack_require__(/*! inherits */ 55); +var util = __webpack_require__(/*! core-util-is */ 55); +util.inherits = __webpack_require__(/*! inherits */ 51); /**/ util.inherits(Transform, Duplex); @@ -67174,7 +66152,7 @@ function done(stream, er, data) { } /***/ }), -/* 107 */ +/* 106 */ /*!***********************************************************!*\ !*** ./node_modules/string_decoder/lib/string_decoder.js ***! \***********************************************************/ @@ -67183,7 +66161,7 @@ function done(stream, er, data) { "use strict"; -var Buffer = __webpack_require__(/*! safe-buffer */ 66).Buffer; +var Buffer = __webpack_require__(/*! safe-buffer */ 63).Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; @@ -67455,77 +66433,7 @@ function simpleEnd(buf) { } /***/ }), -/* 108 */ -/*!************************************************!*\ - !*** ./node_modules/timers-browserify/main.js ***! - \************************************************/ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var apply = Function.prototype.apply; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// setimmediate attaches itself to the global object -__webpack_require__(/*! setimmediate */ 174); -// On some exotic environments, it's not clear which object `setimmeidate` was -// able to install onto. Search each possibility in the same order as the -// `setimmediate` library. -exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || - (typeof global !== "undefined" && global.setImmediate) || - (this && this.setImmediate); -exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || - (typeof global !== "undefined" && global.clearImmediate) || - (this && this.clearImmediate); - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ 48))) - -/***/ }), -/* 109 */ +/* 107 */ /*!**********************************************************************!*\ !*** ./node_modules/readable-stream/lib/internal/streams/destroy.js ***! \**********************************************************************/ @@ -67536,7 +66444,7 @@ exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || /**/ -var processNextTick = __webpack_require__(/*! process-nextick-args */ 67).nextTick; +var processNextTick = __webpack_require__(/*! process-nextick-args */ 64).nextTick; /**/ // undocumented cb() API, needed for core, not for public API @@ -67608,17 +66516,17 @@ module.exports = { }; /***/ }), -/* 110 */ +/* 108 */ /*!*****************************************************************************!*\ !*** ./node_modules/readable-stream/lib/internal/streams/stream-browser.js ***! \*****************************************************************************/ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(/*! events */ 82).EventEmitter; +module.exports = __webpack_require__(/*! events */ 78).EventEmitter; /***/ }), -/* 111 */ +/* 109 */ /*!**************************************************************!*\ !*** ./node_modules/readable-stream/lib/_stream_readable.js ***! \**************************************************************/ @@ -67650,13 +66558,13 @@ module.exports = __webpack_require__(/*! events */ 82).EventEmitter; /**/ -var processNextTick = __webpack_require__(/*! process-nextick-args */ 67).nextTick; +var processNextTick = __webpack_require__(/*! process-nextick-args */ 64).nextTick; /**/ module.exports = Readable; /**/ -var isArray = __webpack_require__(/*! isarray */ 113); +var isArray = __webpack_require__(/*! isarray */ 111); /**/ /**/ @@ -67666,7 +66574,7 @@ var Duplex; Readable.ReadableState = ReadableState; /**/ -var EE = __webpack_require__(/*! events */ 82).EventEmitter; +var EE = __webpack_require__(/*! events */ 78).EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; @@ -67674,12 +66582,12 @@ var EElistenerCount = function (emitter, type) { /**/ /**/ -var Stream = __webpack_require__(/*! ./internal/streams/stream */ 110); +var Stream = __webpack_require__(/*! ./internal/streams/stream */ 108); /**/ /**/ -var Buffer = __webpack_require__(/*! safe-buffer */ 66).Buffer; +var Buffer = __webpack_require__(/*! safe-buffer */ 63).Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); @@ -67691,12 +66599,12 @@ function _isUint8Array(obj) { /**/ /**/ -var util = __webpack_require__(/*! core-util-is */ 59); -util.inherits = __webpack_require__(/*! inherits */ 55); +var util = __webpack_require__(/*! core-util-is */ 55); +util.inherits = __webpack_require__(/*! inherits */ 51); /**/ /**/ -var debugUtil = __webpack_require__(/*! util */ 177); +var debugUtil = __webpack_require__(/*! util */ 175); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); @@ -67705,8 +66613,8 @@ if (debugUtil && debugUtil.debuglog) { } /**/ -var BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ 176); -var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ 109); +var BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ 174); +var destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ 107); var StringDecoder; util.inherits(Readable, Stream); @@ -67726,7 +66634,7 @@ function prependListener(emitter, event, fn) { } function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 52); + Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 48); options = options || {}; @@ -67796,14 +66704,14 @@ function ReadableState(options, stream) { this.decoder = null; this.encoding = null; if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 107).StringDecoder; + if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 106).StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { - Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 52); + Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ 48); if (!(this instanceof Readable)) return new Readable(options); @@ -67952,7 +66860,7 @@ Readable.prototype.isPaused = function () { // backwards compatibility. Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 107).StringDecoder; + if (!StringDecoder) StringDecoder = __webpack_require__(/*! string_decoder/ */ 106).StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; @@ -68640,10 +67548,10 @@ function indexOf(xs, x) { } return -1; } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ 48), __webpack_require__(/*! ./../../process/browser.js */ 60))) +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../webpack/buildin/global.js */ 44), __webpack_require__(/*! ./../../process/browser.js */ 57))) /***/ }), -/* 112 */ +/* 110 */ /*!***********************************************************!*\ !*** ./node_modules/jszip/lib/readable-stream-browser.js ***! \***********************************************************/ @@ -68657,11 +67565,11 @@ function indexOf(xs, x) { * reduce the final size of the bundle (only one stream implementation, not * two). */ -module.exports = __webpack_require__(/*! stream */ 178); +module.exports = __webpack_require__(/*! stream */ 176); /***/ }), -/* 113 */ +/* 111 */ /*!***************************************!*\ !*** ./node_modules/isarray/index.js ***! \***************************************/ @@ -68675,7 +67583,77 @@ module.exports = Array.isArray || function (arr) { /***/ }), -/* 114 */ +/* 112 */ +/*!************************************************!*\ + !*** ./node_modules/timers-browserify/main.js ***! + \************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {var apply = Function.prototype.apply; + +// DOM APIs, for completeness + +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, window, arguments), clearInterval); +}; +exports.clearTimeout = +exports.clearInterval = function(timeout) { + if (timeout) { + timeout.close(); + } +}; + +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; +} +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(window, this._id); +}; + +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; + +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; + +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// setimmediate attaches itself to the global object +__webpack_require__(/*! setimmediate */ 180); +// On some exotic environments, it's not clear which object `setimmeidate` was +// able to install onto. Search each possibility in the same order as the +// `setimmediate` library. +exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || + (typeof global !== "undefined" && global.setImmediate) || + (this && this.setImmediate); +exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || + (typeof global !== "undefined" && global.clearImmediate) || + (this && this.clearImmediate); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ 44))) + +/***/ }), +/* 113 */ /*!*************************************************!*\ !*** ./node_modules/brace/worker/javascript.js ***! \*************************************************/ @@ -68684,6 +67662,234 @@ module.exports = Array.isArray || function (arr) { module.exports.id = 'ace/mode/javascript_worker'; module.exports.src = "\"no use strict\";!function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}}(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return\"Range: [\"+this.start.row+\"/\"+this.start.column+\"] -> [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.columnthis.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&\").replace(/\"/g,\""\").replace(/'/g,\"'\").replace(/i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&¤tRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&®.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&®.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&®.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&¤tFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&¶mScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r   ᠎              \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});"; +/***/ }), +/* 114 */ +/*!************************************************!*\ + !*** ./node_modules/sprintf-js/src/sprintf.js ***! + \************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */ + +!function() { + 'use strict' + + var re = { + not_string: /[^s]/, + not_bool: /[^t]/, + not_type: /[^T]/, + not_primitive: /[^v]/, + number: /[diefg]/, + numeric_arg: /[bcdiefguxX]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[\+\-]/ + } + + function sprintf(key) { + // `arguments` is not an array, but should be fine for this call + return sprintf_format(sprintf_parse(key), arguments) + } + + function vsprintf(fmt, argv) { + return sprintf.apply(null, [fmt].concat(argv || [])) + } + + function sprintf_format(parse_tree, argv) { + var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, match, pad, pad_character, pad_length, is_positive, sign + for (i = 0; i < tree_length; i++) { + if (typeof parse_tree[i] === 'string') { + output += parse_tree[i] + } + else if (Array.isArray(parse_tree[i])) { + match = parse_tree[i] // convenience purposes only + if (match[2]) { // keyword argument + arg = argv[cursor] + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k])) + } + arg = arg[match[2][k]] + } + } + else if (match[1]) { // positional argument (explicit) + arg = argv[match[1]] + } + else { // positional argument (implicit) + arg = argv[cursor++] + } + + if (re.not_type.test(match[8]) && re.not_primitive.test(match[8]) && arg instanceof Function) { + arg = arg() + } + + if (re.numeric_arg.test(match[8]) && (typeof arg !== 'number' && isNaN(arg))) { + throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg)) + } + + if (re.number.test(match[8])) { + is_positive = arg >= 0 + } + + switch (match[8]) { + case 'b': + arg = parseInt(arg, 10).toString(2) + break + case 'c': + arg = String.fromCharCode(parseInt(arg, 10)) + break + case 'd': + case 'i': + arg = parseInt(arg, 10) + break + case 'j': + arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0) + break + case 'e': + arg = match[7] ? parseFloat(arg).toExponential(match[7]) : parseFloat(arg).toExponential() + break + case 'f': + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg) + break + case 'g': + arg = match[7] ? String(Number(arg.toPrecision(match[7]))) : parseFloat(arg) + break + case 'o': + arg = (parseInt(arg, 10) >>> 0).toString(8) + break + case 's': + arg = String(arg) + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 't': + arg = String(!!arg) + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'T': + arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase() + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'u': + arg = parseInt(arg, 10) >>> 0 + break + case 'v': + arg = arg.valueOf() + arg = (match[7] ? arg.substring(0, match[7]) : arg) + break + case 'x': + arg = (parseInt(arg, 10) >>> 0).toString(16) + break + case 'X': + arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase() + break + } + if (re.json.test(match[8])) { + output += arg + } + else { + if (re.number.test(match[8]) && (!is_positive || match[3])) { + sign = is_positive ? '+' : '-' + arg = arg.toString().replace(re.sign, '') + } + else { + sign = '' + } + pad_character = match[4] ? match[4] === '0' ? '0' : match[4].charAt(1) : ' ' + pad_length = match[6] - (sign + arg).length + pad = match[6] ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '' + output += match[5] ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg) + } + } + } + return output + } + + var sprintf_cache = Object.create(null) + + function sprintf_parse(fmt) { + if (sprintf_cache[fmt]) { + return sprintf_cache[fmt] + } + + var _fmt = fmt, match, parse_tree = [], arg_names = 0 + while (_fmt) { + if ((match = re.text.exec(_fmt)) !== null) { + parse_tree.push(match[0]) + } + else if ((match = re.modulo.exec(_fmt)) !== null) { + parse_tree.push('%') + } + else if ((match = re.placeholder.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1 + var field_list = [], replacement_field = match[2], field_match = [] + if ((field_match = re.key.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = re.key_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else if ((field_match = re.index_access.exec(replacement_field)) !== null) { + field_list.push(field_match[1]) + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + } + } + else { + throw new SyntaxError('[sprintf] failed to parse named argument key') + } + match[2] = field_list + } + else { + arg_names |= 2 + } + if (arg_names === 3) { + throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported') + } + parse_tree.push(match) + } + else { + throw new SyntaxError('[sprintf] unexpected placeholder') + } + _fmt = _fmt.substring(match[0].length) + } + return sprintf_cache[fmt] = parse_tree + } + + /** + * export to either browser or node.js + */ + /* eslint-disable quote-props */ + if (true) { + exports['sprintf'] = sprintf + exports['vsprintf'] = vsprintf + } + if (typeof window !== 'undefined') { + window['sprintf'] = sprintf + window['vsprintf'] = vsprintf + + if (true) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { + return { + 'sprintf': sprintf, + 'vsprintf': vsprintf + } + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) + } + } + /* eslint-enable quote-props */ +}() + + /***/ }), /* 115 */ /*!*********************************!*\ @@ -68732,7 +67938,7 @@ module.exports = v4; "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "factionInvitationBoxCreate", function() { return factionInvitationBoxCreate; }); -/* harmony import */ var _src_Faction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Faction.js */ 11); +/* harmony import */ var _src_Faction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/Faction.js */ 9); /* harmony import */ var _src_engine_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../src/engine.js */ 5); /* harmony import */ var _src_Player_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Player.js */ 0); /* harmony import */ var _HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./HelperFunctions.js */ 1); @@ -68811,11 +68017,11 @@ function factionInvitationBoxCreate(faction) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "infiltrationBoxCreate", function() { return infiltrationBoxCreate; }); -/* harmony import */ var _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/BitNode.js */ 15); +/* harmony import */ var _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../src/BitNode.js */ 12); /* harmony import */ var _src_Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../src/Constants.js */ 3); -/* harmony import */ var _src_Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Faction.js */ 11); +/* harmony import */ var _src_Faction_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../src/Faction.js */ 9); /* harmony import */ var _src_Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../src/Player.js */ 0); -/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./DialogBox.js */ 7); +/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./DialogBox.js */ 6); /* harmony import */ var _HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./HelperFunctions.js */ 1); /* harmony import */ var _StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./StringHelperFunctions.js */ 2); @@ -68943,11 +68149,11 @@ function infiltrationBoxCreate(inst) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "beginInfiltration", function() { return beginInfiltration; }); -/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 15); +/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./BitNode.js */ 12); /* harmony import */ var _Constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Constants.js */ 3); /* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.js */ 5); /* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Player.js */ 0); -/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 7); +/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6); /* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1); /* harmony import */ var _utils_InfiltrationBox_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/InfiltrationBox.js */ 117); /* harmony import */ var _utils_StringHelperFunctions_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/StringHelperFunctions.js */ 2); @@ -69968,7 +69174,7 @@ var saveAs = saveAs || (function(view) { if (typeof module !== "undefined" && module.exports) { module.exports.saveAs = saveAs; -} else if (("function" !== "undefined" && __webpack_require__(/*! !webpack amd define */ 83) !== null) && (__webpack_require__(/*! !webpack amd options */ 130) !== null)) { +} else if (("function" !== "undefined" && __webpack_require__(/*! !webpack amd define */ 79) !== null) && (__webpack_require__(/*! !webpack amd options */ 129) !== null)) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return saveAs; }).call(exports, __webpack_require__, exports, module), @@ -70021,10 +69227,10 @@ function JSZip() { return newObj; }; } -JSZip.prototype = __webpack_require__(/*! ./object */ 181); -JSZip.prototype.loadAsync = __webpack_require__(/*! ./load */ 135); -JSZip.support = __webpack_require__(/*! ./support */ 50); -JSZip.defaults = __webpack_require__(/*! ./defaults */ 99); +JSZip.prototype = __webpack_require__(/*! ./object */ 179); +JSZip.prototype.loadAsync = __webpack_require__(/*! ./load */ 134); +JSZip.support = __webpack_require__(/*! ./support */ 46); +JSZip.defaults = __webpack_require__(/*! ./defaults */ 98); // TODO find a better way to handle this version, // a require('package.json').version doesn't work with webpack, see #327 @@ -70034,7 +69240,7 @@ JSZip.loadAsync = function (content, options) { return new JSZip().loadAsync(content, options); }; -JSZip.external = __webpack_require__(/*! ./external */ 58); +JSZip.external = __webpack_require__(/*! ./external */ 54); module.exports = JSZip; @@ -70130,7 +69336,7 @@ __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeEnvHeader", function() { return makeEnvHeader; }); /* harmony import */ var uuid_v4__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uuid/v4 */ 115); /* harmony import */ var uuid_v4__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(uuid_v4__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sprintf-js */ 68); +/* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! sprintf-js */ 114); /* harmony import */ var sprintf_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(sprintf_js__WEBPACK_IMPORTED_MODULE_1__); // A utility function that adds a preamble to each Netscript JS // script. This preamble will set all the global functions and @@ -70177,6 +69383,10012 @@ function makeEnvHeader(uuid) { /***/ }), /* 129 */ +/*!****************************************!*\ + !*** (webpack)/buildin/amd-options.js ***! + \****************************************/ +/***/ (function(module, exports) { + +/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ +module.exports = __webpack_amd_options__; + +/* WEBPACK VAR INJECTION */}.call(this, {})) + +/***/ }), +/* 130 */ +/*!********************************************!*\ + !*** ./node_modules/jszip/lib/zipEntry.js ***! + \********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var readerFor = __webpack_require__(/*! ./reader/readerFor */ 87); +var utils = __webpack_require__(/*! ./utils */ 28); +var CompressedObject = __webpack_require__(/*! ./compressedObject */ 73); +var crc32fn = __webpack_require__(/*! ./crc32 */ 72); +var utf8 = __webpack_require__(/*! ./utf8 */ 52); +var compressions = __webpack_require__(/*! ./compressions */ 94); +var support = __webpack_require__(/*! ./support */ 46); + +var MADE_BY_DOS = 0x00; +var MADE_BY_UNIX = 0x03; + +/** + * Find a compression registered in JSZip. + * @param {string} compressionMethod the method magic to find. + * @return {Object|null} the JSZip compression object, null if none found. + */ +var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!compressions.hasOwnProperty(method)) { + continue; + } + if (compressions[method].magic === compressionMethod) { + return compressions[method]; + } + } + return null; +}; + +// class ZipEntry {{{ +/** + * An entry in the zip file. + * @constructor + * @param {Object} options Options of the current file. + * @param {Object} loadOptions Options for loading the stream. + */ +function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; +} +ZipEntry.prototype = { + /** + * say if the file is encrypted. + * @return {boolean} true if the file is encrypted, false otherwise. + */ + isEncrypted: function() { + // bit 1 is set + return (this.bitFlag & 0x0001) === 0x0001; + }, + /** + * say if the file has utf-8 filename/comment. + * @return {boolean} true if the filename/comment is in utf-8, false otherwise. + */ + useUTF8: function() { + // bit 11 is set + return (this.bitFlag & 0x0800) === 0x0800; + }, + /** + * Read the local part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + + // we already know everything from the central dir ! + // If the central dir data are false, we are doomed. + // On the bright side, the local part is scary : zip64, data descriptors, both, etc. + // The less data we get here, the more reliable this should be. + // Let's skip the whole header and dash to the data ! + reader.skip(22); + // in some zip created on windows, the filename stored in the central dir contains \ instead of /. + // Strangely, the filename here is OK. + // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes + // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... + // Search "unzip mismatching "local" filename continuing with "central" filename version" on + // the internet. + // + // I think I see the logic here : the central directory is used to display + // content and the local directory is used to extract the files. Mixing / and \ + // may be used to display \ to windows users and use / when extracting the files. + // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir + // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding. + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + + if (this.compressedSize === -1 || this.uncompressedSize === -1) { + throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); + } + + compression = findCompression(this.compressionMethod); + if (compression === null) { // no compression found + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + // this.versionNeeded = reader.readInt(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + + if (this.isEncrypted()) { + throw new Error("Encrypted zip are not supported"); + } + + // will be read in the local part, see the comments there + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + + /** + * Parse the external file attributes and get the unix/dos permissions. + */ + processAttributes: function () { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + + // Check if we have the DOS directory flag set. + // We look for it in the DOS and UNIX permissions + // but some unknown platform could set it as a compatibility flag. + this.dir = this.externalFileAttributes & 0x0010 ? true : false; + + if(madeBy === MADE_BY_DOS) { + // first 6 bits (0 to 5) + this.dosPermissions = this.externalFileAttributes & 0x3F; + } + + if(madeBy === MADE_BY_UNIX) { + this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; + // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); + } + + // fail safe : if the name ends with a / it probably means a folder + if (!this.dir && this.fileNameStr.slice(-1) === '/') { + this.dir = true; + } + }, + + /** + * Parse the ZIP64 extra field and merge the info in the current ZipEntry. + * @param {DataReader} reader the reader to use. + */ + parseZIP64ExtraField: function(reader) { + + if (!this.extraFields[0x0001]) { + return; + } + + // should be something, preparing the extra reader + var extraReader = readerFor(this.extraFields[0x0001].value); + + // I really hope that these 64bits integer can fit in 32 bits integer, because js + // won't let us have more. + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + this.uncompressedSize = extraReader.readInt(8); + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { + this.compressedSize = extraReader.readInt(8); + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + this.localHeaderOffset = extraReader.readInt(8); + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + this.diskNumberStart = extraReader.readInt(4); + } + }, + /** + * Read the central part of a zip file and add the info in this object. + * @param {DataReader} reader the reader to use. + */ + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, + extraFieldId, + extraFieldLength, + extraFieldValue; + + if (!this.extraFields) { + this.extraFields = {}; + } + + while (reader.index < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + /** + * Apply an UTF8 transformation if needed. + */ + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) { + this.fileNameStr = upath; + } else { + // ASCII text or unsupported code page + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) { + this.fileCommentStr = ucomment; + } else { + // ASCII text or unsupported code page + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + + /** + * Find the unicode path declared in the extra field, if any. + * @return {String} the unicode path, null otherwise. + */ + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[0x7075]; + if (upathField) { + var extraReader = readerFor(upathField.value); + + // wrong version + if (extraReader.readInt(1) !== 1) { + return null; + } + + // the crc of the filename changed, this field is out of date. + if (crc32fn(this.fileName) !== extraReader.readInt(4)) { + return null; + } + + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + + /** + * Find the unicode comment declared in the extra field, if any. + * @return {String} the unicode comment, null otherwise. + */ + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[0x6375]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + + // wrong version + if (extraReader.readInt(1) !== 1) { + return null; + } + + // the crc of the comment changed, this field is out of date. + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { + return null; + } + + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } +}; +module.exports = ZipEntry; + + +/***/ }), +/* 131 */ +/*!***********************************************************!*\ + !*** ./node_modules/jszip/lib/reader/NodeBufferReader.js ***! + \***********************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 84); +var utils = __webpack_require__(/*! ../utils */ 28); + +function NodeBufferReader(data) { + Uint8ArrayReader.call(this, data); +} +utils.inherits(NodeBufferReader, Uint8ArrayReader); + +/** + * @see DataReader.readData + */ +NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; +}; +module.exports = NodeBufferReader; + + +/***/ }), +/* 132 */ +/*!*******************************************************!*\ + !*** ./node_modules/jszip/lib/reader/StringReader.js ***! + \*******************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var DataReader = __webpack_require__(/*! ./DataReader */ 85); +var utils = __webpack_require__(/*! ../utils */ 28); + +function StringReader(data) { + DataReader.call(this, data); +} +utils.inherits(StringReader, DataReader); +/** + * @see DataReader.byteAt + */ +StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); +}; +/** + * @see DataReader.lastIndexOfSignature + */ +StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; +}; +/** + * @see DataReader.readAndCheckSignature + */ +StringReader.prototype.readAndCheckSignature = function (sig) { + var data = this.readData(4); + return sig === data; +}; +/** + * @see DataReader.readData + */ +StringReader.prototype.readData = function(size) { + this.checkOffset(size); + // this will work because the constructor applied the "& 0xff" mask. + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; +}; +module.exports = StringReader; + + +/***/ }), +/* 133 */ +/*!**********************************************!*\ + !*** ./node_modules/jszip/lib/zipEntries.js ***! + \**********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var readerFor = __webpack_require__(/*! ./reader/readerFor */ 87); +var utils = __webpack_require__(/*! ./utils */ 28); +var sig = __webpack_require__(/*! ./signature */ 88); +var ZipEntry = __webpack_require__(/*! ./zipEntry */ 130); +var utf8 = __webpack_require__(/*! ./utf8 */ 52); +var support = __webpack_require__(/*! ./support */ 46); +// class ZipEntries {{{ +/** + * All the entries in the zip file. + * @constructor + * @param {Object} loadOptions Options for loading the stream. + */ +function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; +} +ZipEntries.prototype = { + /** + * Check that the reader is on the specified signature. + * @param {string} expectedSignature the expected signature. + * @throws {Error} if it is an other signature. + */ + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + /** + * Check if the given signature is at the given index. + * @param {number} askedIndex the index to check. + * @param {string} expectedSignature the signature to expect. + * @return {boolean} true if the signature is here, false otherwise. + */ + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + /** + * Read the end of the central directory. + */ + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + + this.zipCommentLength = this.reader.readInt(2); + // warning : the encoding depends of the system locale + // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. + // On a windows machine, this field is encoded with the localized windows code page. + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + // To get consistent behavior with the generation part, we will assume that + // this is utf8 encoded unless specified otherwise. + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + /** + * Read the end of the Zip 64 central directory. + * Not merged with the method readEndOfCentral : + * The end of central can coexist with its Zip64 brother, + * I don't want to read the wrong number of bytes ! + */ + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + // this.versionMadeBy = this.reader.readString(2); + // this.versionNeeded = this.reader.readInt(2); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, + index = 0, + extraFieldId, + extraFieldLength, + extraFieldValue; + while (index < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + /** + * Read the end of the Zip 64 central directory locator. + */ + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { + throw new Error("Multi-volumes zip are not supported"); + } + }, + /** + * Read the local files, based on the offset read in the central part. + */ + readLocalFiles: function() { + var i, file; + for (i = 0; i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + /** + * Read the central directory. + */ + readCentralDir: function() { + var file; + + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ + zip64: this.zip64 + }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + // We expected some records but couldn't find ANY. + // This is really suspicious, as if something went wrong. + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + // We found some records but not all. + // Something is wrong but we got something for the user: no error here. + // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); + } + } + }, + /** + * Read the end of central directory. + */ + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { + // Check if the content is a truncated zip or complete garbage. + // A "LOCAL_FILE_HEADER" is not required at the beginning (auto + // extractible zip for example) but it can give a good hint. + // If an ajax request was used without responseType, we will also + // get unreadable data. + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); + + if (isGarbage) { + throw new Error("Can't find end of central directory : is this a zip file ? " + + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + } else { + throw new Error("Corrupted zip: can't find end of central directory"); + } + + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + + + /* extract from the zip spec : + 4) If one of the fields in the end of central directory + record is too small to hold required data, the field + should be set to -1 (0xFFFF or 0xFFFFFFFF) and the + ZIP64 format record should be created. + 5) The end of central directory record and the + Zip64 end of central directory locator record must + reside on the same disk when splitting or spanning + an archive. + */ + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + + /* + Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from + the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents + all numbers as 64-bit double precision IEEE 754 floating point numbers. + So, we have 53bits for integers and bitwise operations treat everything as 32bits. + see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators + and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 + */ + + // should look for a zip64 EOCD locator + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + } + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + + // now the zip64 EOCD record + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + // console.warn("ZIP64 end of central directory not where expected."); + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator + expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; + } + + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + + if (extraBytes > 0) { + // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + // The offsets seem wrong, but we have something at the specified offset. + // So… we keep it. + } else { + // the offset is wrong, update the "zero" of the reader + // this happens if data has been prepended (crx files for example) + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function(data) { + this.reader = readerFor(data); + }, + /** + * Read a zip file and create ZipEntries. + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. + */ + load: function(data) { + this.prepareReader(data); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } +}; +// }}} end of ZipEntries +module.exports = ZipEntries; + + +/***/ }), +/* 134 */ +/*!****************************************!*\ + !*** ./node_modules/jszip/lib/load.js ***! + \****************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var utils = __webpack_require__(/*! ./utils */ 28); +var external = __webpack_require__(/*! ./external */ 54); +var utf8 = __webpack_require__(/*! ./utf8 */ 52); +var utils = __webpack_require__(/*! ./utils */ 28); +var ZipEntries = __webpack_require__(/*! ./zipEntries */ 133); +var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 95); +var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62); + +/** + * Check the CRC32 of an entry. + * @param {ZipEntry} zipEntry the zip entry to check. + * @return {Promise} the result. + */ +function checkEntryCRC32(zipEntry) { + return new external.Promise(function (resolve, reject) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); + worker.on("error", function (e) { + reject(e); + }) + .on("end", function () { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { + reject(new Error("Corrupted zip : CRC32 mismatch")); + } else { + resolve(); + } + }) + .resume(); + }); +} + +module.exports = function(data, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + + if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { + return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); + } + + return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64) + .then(function(data) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) { + for (var i = 0; i < files.length; i++) { + promises.push(checkEntryCRC32(files[i])); + } + } + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0; i < files.length; i++) { + var input = files[i]; + zip.file(input.fileNameStr, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment : input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions : input.unixPermissions, + dosPermissions : input.dosPermissions, + createFolders: options.createFolders + }); + } + if (zipEntries.zipComment.length) { + zip.comment = zipEntries.zipComment; + } + + return zip; + }); +}; + + +/***/ }), +/* 135 */ +/*!*******************************************************************!*\ + !*** ./node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js ***! + \*******************************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ../utils */ 28); +var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 34); + +/** + * A worker that use a nodejs stream as source. + * @constructor + * @param {String} filename the name of the file entry for this stream. + * @param {Readable} stream the nodejs stream. + */ +function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); +} + +utils.inherits(NodejsStreamInputAdapter, GenericWorker); + +/** + * Prepare the stream and bind the callbacks on it. + * Do this ASAP on node 0.10 ! A lazy binding doesn't always work. + * @param {Stream} stream the nodejs stream to use. + */ +NodejsStreamInputAdapter.prototype._bindStream = function (stream) { + var self = this; + this._stream = stream; + stream.pause(); + stream + .on("data", function (chunk) { + self.push({ + data: chunk, + meta : { + percent : 0 + } + }); + }) + .on("error", function (e) { + if(self.isPaused) { + this.generatedError = e; + } else { + self.error(e); + } + }) + .on("end", function () { + if(self.isPaused) { + self._upstreamEnded = true; + } else { + self.end(); + } + }); +}; +NodejsStreamInputAdapter.prototype.pause = function () { + if(!GenericWorker.prototype.pause.call(this)) { + return false; + } + this._stream.pause(); + return true; +}; +NodejsStreamInputAdapter.prototype.resume = function () { + if(!GenericWorker.prototype.resume.call(this)) { + return false; + } + + if(this._upstreamEnded) { + this.end(); + } else { + this._stream.resume(); + } + + return true; +}; + +module.exports = NodejsStreamInputAdapter; + + +/***/ }), +/* 136 */ +/*!**********************************************************!*\ + !*** ./node_modules/jszip/lib/generate/ZipFileWorker.js ***! + \**********************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var utils = __webpack_require__(/*! ../utils */ 28); +var GenericWorker = __webpack_require__(/*! ../stream/GenericWorker */ 34); +var utf8 = __webpack_require__(/*! ../utf8 */ 52); +var crc32 = __webpack_require__(/*! ../crc32 */ 72); +var signature = __webpack_require__(/*! ../signature */ 88); + +/** + * Transform an integer into a string in hexadecimal. + * @private + * @param {number} dec the number to convert. + * @param {number} bytes the number of bytes to generate. + * @returns {string} the result. + */ +var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0; i < bytes; i++) { + hex += String.fromCharCode(dec & 0xff); + dec = dec >>> 8; + } + return hex; +}; + +/** + * Generate the UNIX part of the external file attributes. + * @param {Object} unixPermissions the unix permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : + * + * TTTTsstrwxrwxrwx0000000000ADVSHR + * ^^^^____________________________ file type, see zipinfo.c (UNX_*) + * ^^^_________________________ setuid, setgid, sticky + * ^^^^^^^^^________________ permissions + * ^^^^^^^^^^______ not used ? + * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only + */ +var generateUnixExternalFileAttr = function (unixPermissions, isDir) { + + var result = unixPermissions; + if (!unixPermissions) { + // I can't use octal values in strict mode, hence the hexa. + // 040775 => 0x41fd + // 0100664 => 0x81b4 + result = isDir ? 0x41fd : 0x81b4; + } + return (result & 0xFFFF) << 16; +}; + +/** + * Generate the DOS part of the external file attributes. + * @param {Object} dosPermissions the dos permissions or null. + * @param {Boolean} isDir true if the entry is a directory, false otherwise. + * @return {Number} a 32 bit integer. + * + * Bit 0 Read-Only + * Bit 1 Hidden + * Bit 2 System + * Bit 3 Volume Label + * Bit 4 Directory + * Bit 5 Archive + */ +var generateDosExternalFileAttr = function (dosPermissions, isDir) { + + // the dir flag is already set for compatibility + return (dosPermissions || 0) & 0x3F; +}; + +/** + * Generate the various parts used in the construction of the final zip file. + * @param {Object} streamInfo the hash with informations about the compressed file. + * @param {Boolean} streamedContent is the content streamed ? + * @param {Boolean} streamingEnded is the stream finished ? + * @param {number} offset the current offset from the start of the zip file. + * @param {String} platform let's pretend we are this platform (change platform dependents fields) + * @param {Function} encodeFileName the function to encode the file name / comment. + * @return {Object} the zip parts. + */ +var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo['file'], + compression = streamInfo['compression'], + useCustomEncoding = encodeFileName !== utf8.utf8encode, + encodedFileName = utils.transformTo("string", encodeFileName(file.name)), + utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), + comment = file.comment, + encodedComment = utils.transformTo("string", encodeFileName(comment)), + utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), + useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, + useUTF8ForComment = utfEncodedComment.length !== comment.length, + dosTime, + dosDate, + extraFields = "", + unicodePathExtraField = "", + unicodeCommentExtraField = "", + dir = file.dir, + date = file.date; + + + var dataInfo = { + crc32 : 0, + compressedSize : 0, + uncompressedSize : 0 + }; + + // if the content is streamed, the sizes/crc32 are only available AFTER + // the end of the stream. + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo['crc32']; + dataInfo.compressedSize = streamInfo['compressedSize']; + dataInfo.uncompressedSize = streamInfo['uncompressedSize']; + } + + var bitflag = 0; + if (streamedContent) { + // Bit 3: the sizes/crc32 are set to zero in the local header. + // The correct values are put in the data descriptor immediately + // following the compressed data. + bitflag |= 0x0008; + } + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { + // Bit 11: Language encoding flag (EFS). + bitflag |= 0x0800; + } + + + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + // dos or unix, we set the dos dir flag + extFileAttr |= 0x00010; + } + if(platform === "UNIX") { + versionMadeBy = 0x031E; // UNIX, version 3.0 + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { // DOS or other, fallback to DOS + versionMadeBy = 0x0014; // DOS, version 2.0 + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + + // date + // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html + // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html + // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html + + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | (date.getUTCMonth() + 1); + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + + if (useUTF8ForFileName) { + // set the unicode path extra field. unzip needs at least one extra + // field to correctly handle unicode path, so using the path is as good + // as any other information. This could improve the situation with + // other archive managers too. + // This field is usually used without the utf8 flag, with a non + // unicode path in the header (winrar, winzip). This helps (a bit) + // with the messy Windows' default compressed folders feature but + // breaks on p7zip which doesn't seek the unicode path extra field. + // So for now, UTF-8 everywhere ! + unicodePathExtraField = + // Version + decToHex(1, 1) + + // NameCRC32 + decToHex(crc32(encodedFileName), 4) + + // UnicodeName + utfEncodedFileName; + + extraFields += + // Info-ZIP Unicode Path Extra Field + "\x75\x70" + + // size + decToHex(unicodePathExtraField.length, 2) + + // content + unicodePathExtraField; + } + + if(useUTF8ForComment) { + + unicodeCommentExtraField = + // Version + decToHex(1, 1) + + // CommentCRC32 + decToHex(crc32(encodedComment), 4) + + // UnicodeName + utfEncodedComment; + + extraFields += + // Info-ZIP Unicode Path Extra Field + "\x75\x63" + + // size + decToHex(unicodeCommentExtraField.length, 2) + + // content + unicodeCommentExtraField; + } + + var header = ""; + + // version needed to extract + header += "\x0A\x00"; + // general purpose bit flag + header += decToHex(bitflag, 2); + // compression method + header += compression.magic; + // last mod file time + header += decToHex(dosTime, 2); + // last mod file date + header += decToHex(dosDate, 2); + // crc-32 + header += decToHex(dataInfo.crc32, 4); + // compressed size + header += decToHex(dataInfo.compressedSize, 4); + // uncompressed size + header += decToHex(dataInfo.uncompressedSize, 4); + // file name length + header += decToHex(encodedFileName.length, 2); + // extra field length + header += decToHex(extraFields.length, 2); + + + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; + + var dirRecord = signature.CENTRAL_FILE_HEADER + + // version made by (00: DOS) + decToHex(versionMadeBy, 2) + + // file header (common to file and central directory) + header + + // file comment length + decToHex(encodedComment.length, 2) + + // disk number start + "\x00\x00" + + // internal file attributes TODO + "\x00\x00" + + // external file attributes + decToHex(extFileAttr, 4) + + // relative offset of local header + decToHex(offset, 4) + + // file name + encodedFileName + + // extra field + extraFields + + // file comment + encodedComment; + + return { + fileRecord: fileRecord, + dirRecord: dirRecord + }; +}; + +/** + * Generate the EOCD record. + * @param {Number} entriesCount the number of entries in the zip file. + * @param {Number} centralDirLength the length (in bytes) of the central dir. + * @param {Number} localDirLength the length (in bytes) of the local dir. + * @param {String} comment the zip file comment as a binary string. + * @param {Function} encodeFileName the function to encode the comment. + * @return {String} the EOCD record. + */ +var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + + // end of central dir signature + dirEnd = signature.CENTRAL_DIRECTORY_END + + // number of this disk + "\x00\x00" + + // number of the disk with the start of the central directory + "\x00\x00" + + // total number of entries in the central directory on this disk + decToHex(entriesCount, 2) + + // total number of entries in the central directory + decToHex(entriesCount, 2) + + // size of the central directory 4 bytes + decToHex(centralDirLength, 4) + + // offset of start of central directory with respect to the starting disk number + decToHex(localDirLength, 4) + + // .ZIP file comment length + decToHex(encodedComment.length, 2) + + // .ZIP file comment + encodedComment; + + return dirEnd; +}; + +/** + * Generate data descriptors for a file entry. + * @param {Object} streamInfo the hash generated by a worker, containing informations + * on the file entry. + * @return {String} the data descriptors. + */ +var generateDataDescriptors = function (streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + + // crc-32 4 bytes + decToHex(streamInfo['crc32'], 4) + + // compressed size 4 bytes + decToHex(streamInfo['compressedSize'], 4) + + // uncompressed size 4 bytes + decToHex(streamInfo['uncompressedSize'], 4); + + return descriptor; +}; + + +/** + * A worker to concatenate other workers to create a zip file. + * @param {Boolean} streamFiles `true` to stream the content of the files, + * `false` to accumulate it. + * @param {String} comment the comment to use. + * @param {String} platform the platform to use, "UNIX" or "DOS". + * @param {Function} encodeFileName the function to encode file names and comments. + */ +function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + // The number of bytes written so far. This doesn't count accumulated chunks. + this.bytesWritten = 0; + // The comment of the zip file + this.zipComment = comment; + // The platform "generating" the zip file. + this.zipPlatform = platform; + // the function to encode file names and comments. + this.encodeFileName = encodeFileName; + // Should we stream the content of the files ? + this.streamFiles = streamFiles; + // If `streamFiles` is false, we will need to accumulate the content of the + // files to calculate sizes / crc32 (and write them *before* the content). + // This boolean indicates if we are accumulating chunks (it will change a lot + // during the lifetime of this worker). + this.accumulate = false; + // The buffer receiving chunks when accumulating content. + this.contentBuffer = []; + // The list of generated directory records. + this.dirRecords = []; + // The offset (in bytes) from the beginning of the zip file for the current source. + this.currentSourceOffset = 0; + // The total number of entries in this zip file. + this.entriesCount = 0; + // the name of the file currently being added, null when handling the end of the zip file. + // Used for the emited metadata. + this.currentFile = null; + + + + this._sources = []; +} +utils.inherits(ZipFileWorker, GenericWorker); + +/** + * @see GenericWorker.push + */ +ZipFileWorker.prototype.push = function (chunk) { + + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + + if(this.accumulate) { + this.contentBuffer.push(chunk); + } else { + this.bytesWritten += chunk.data.length; + + GenericWorker.prototype.push.call(this, { + data : chunk.data, + meta : { + currentFile : this.currentFile, + percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } +}; + +/** + * The worker started a new source (an other worker). + * @param {Object} streamInfo the streamInfo object from the new source. + */ +ZipFileWorker.prototype.openedSource = function (streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo['file'].name; + + var streamedContent = this.streamFiles && !streamInfo['file'].dir; + + // don't stream folders (because they don't have any content) + if(streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data : record.fileRecord, + meta : {percent:0} + }); + } else { + // we need to wait for the whole file before pushing anything + this.accumulate = true; + } +}; + +/** + * The worker finished a source (an other worker). + * @param {Object} streamInfo the streamInfo object from the finished source. + */ +ZipFileWorker.prototype.closedSource = function (streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo['file'].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + + this.dirRecords.push(record.dirRecord); + if(streamedContent) { + // after the streamed file, we put data descriptors + this.push({ + data : generateDataDescriptors(streamInfo), + meta : {percent:100} + }); + } else { + // the content wasn't streamed, we need to push everything now + // first the file record, then the content + this.push({ + data : record.fileRecord, + meta : {percent:0} + }); + while(this.contentBuffer.length) { + this.push(this.contentBuffer.shift()); + } + } + this.currentFile = null; +}; + +/** + * @see GenericWorker.flush + */ +ZipFileWorker.prototype.flush = function () { + + var localDirLength = this.bytesWritten; + for(var i = 0; i < this.dirRecords.length; i++) { + this.push({ + data : this.dirRecords[i], + meta : {percent:100} + }); + } + var centralDirLength = this.bytesWritten - localDirLength; + + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + + this.push({ + data : dirEnd, + meta : {percent:100} + }); +}; + +/** + * Prepare the next source to be read. + */ +ZipFileWorker.prototype.prepareNextSource = function () { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) { + this.previous.pause(); + } else { + this.previous.resume(); + } +}; + +/** + * @see GenericWorker.registerPrevious + */ +ZipFileWorker.prototype.registerPrevious = function (previous) { + this._sources.push(previous); + var self = this; + + previous.on('data', function (chunk) { + self.processChunk(chunk); + }); + previous.on('end', function () { + self.closedSource(self.previous.streamInfo); + if(self._sources.length) { + self.prepareNextSource(); + } else { + self.end(); + } + }); + previous.on('error', function (e) { + self.error(e); + }); + return this; +}; + +/** + * @see GenericWorker.resume + */ +ZipFileWorker.prototype.resume = function () { + if(!GenericWorker.prototype.resume.call(this)) { + return false; + } + + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } +}; + +/** + * @see GenericWorker.error + */ +ZipFileWorker.prototype.error = function (e) { + var sources = this._sources; + if(!GenericWorker.prototype.error.call(this, e)) { + return false; + } + for(var i = 0; i < sources.length; i++) { + try { + sources[i].error(e); + } catch(e) { + // the `error` exploded, nothing to do + } + } + return true; +}; + +/** + * @see GenericWorker.lock + */ +ZipFileWorker.prototype.lock = function () { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for(var i = 0; i < sources.length; i++) { + sources[i].lock(); + } +}; + +module.exports = ZipFileWorker; + + +/***/ }), +/* 137 */ +/*!************************************************!*\ + !*** ./node_modules/pako/lib/zlib/gzheader.js ***! + \************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function GZheader() { + /* true if compressed data believed to be text */ + this.text = 0; + /* modification time */ + this.time = 0; + /* extra flags (not used when writing a gzip file) */ + this.xflags = 0; + /* operating system */ + this.os = 0; + /* pointer to extra field or Z_NULL if none */ + this.extra = null; + /* extra field length (valid if extra != Z_NULL) */ + this.extra_len = 0; // Actually, we don't need it in JS, + // but leave for few code modifications + + // + // Setup limits is not necessary because in js we should not preallocate memory + // for inflate use constant limit in 65536 bytes + // + + /* space at extra (only when reading header) */ + // this.extra_max = 0; + /* pointer to zero-terminated file name or Z_NULL */ + this.name = ''; + /* space at name (only when reading header) */ + // this.name_max = 0; + /* pointer to zero-terminated comment or Z_NULL */ + this.comment = ''; + /* space at comment (only when reading header) */ + // this.comm_max = 0; + /* true if there was or will be a header crc */ + this.hcrc = 0; + /* true when done reading gzip header (not used when writing a gzip file) */ + this.done = false; +} + +module.exports = GZheader; + + +/***/ }), +/* 138 */ +/*!************************************************!*\ + !*** ./node_modules/pako/lib/zlib/inftrees.js ***! + \************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(/*! ../utils/common */ 45); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + + +/***/ }), +/* 139 */ +/*!***********************************************!*\ + !*** ./node_modules/pako/lib/zlib/inffast.js ***! + \***********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + + +/***/ }), +/* 140 */ +/*!***********************************************!*\ + !*** ./node_modules/pako/lib/zlib/inflate.js ***! + \***********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(/*! ../utils/common */ 45); +var adler32 = __webpack_require__(/*! ./adler32 */ 93); +var crc32 = __webpack_require__(/*! ./crc32 */ 92); +var inflate_fast = __webpack_require__(/*! ./inffast */ 139); +var inflate_table = __webpack_require__(/*! ./inftrees */ 138); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + + +/***/ }), +/* 141 */ +/*!******************************************!*\ + !*** ./node_modules/pako/lib/inflate.js ***! + \******************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + + +var zlib_inflate = __webpack_require__(/*! ./zlib/inflate */ 140); +var utils = __webpack_require__(/*! ./utils/common */ 45); +var strings = __webpack_require__(/*! ./utils/strings */ 91); +var c = __webpack_require__(/*! ./zlib/constants */ 89); +var msg = __webpack_require__(/*! ./zlib/messages */ 71); +var ZStream = __webpack_require__(/*! ./zlib/zstream */ 90); +var GZheader = __webpack_require__(/*! ./zlib/gzheader */ 137); + +var toString = Object.prototype.toString; + +/** + * class Inflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[inflate]] + * and [[inflateRaw]]. + **/ + +/* internal + * inflate.chunks -> Array + * + * Chunks of output data, if [[Inflate#onData]] not overridden. + **/ + +/** + * Inflate.result -> Uint8Array|Array|String + * + * Uncompressed result, generated by default [[Inflate#onData]] + * and [[Inflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Inflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Inflate.err -> Number + * + * Error code after inflate finished. 0 (Z_OK) on success. + * Should be checked if broken data possible. + **/ + +/** + * Inflate.msg -> String + * + * Error message, if [[Inflate.err]] != 0 + **/ + + +/** + * new Inflate(options) + * - options (Object): zlib inflate options. + * + * Creates new inflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `windowBits` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw inflate + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * By default, when no options set, autodetect deflate/gzip data format via + * wrapper header. + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var inflate = new pako.Inflate({ level: 3}); + * + * inflate.push(chunk1, false); + * inflate.push(chunk2, true); // true -> last chunk + * + * if (inflate.err) { throw new Error(inflate.err); } + * + * console.log(inflate.result); + * ``` + **/ +function Inflate(options) { + if (!(this instanceof Inflate)) return new Inflate(options); + + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: '' + }, options || {}); + + var opt = this.options; + + // Force window size for `raw` data, if not set directly, + // because we have no header for autodetect. + if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { opt.windowBits = -15; } + } + + // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate + if ((opt.windowBits >= 0) && (opt.windowBits < 16) && + !(options && options.windowBits)) { + opt.windowBits += 32; + } + + // Gzip header has no info about windows size, we can do autodetect only + // for deflate. So, if window size not set, force it to max when gzip possible + if ((opt.windowBits > 15) && (opt.windowBits < 48)) { + // bit 3 (16) -> gzipped data + // bit 4 (32) -> autodetect gzip/deflate + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_inflate.inflateInit2( + this.strm, + opt.windowBits + ); + + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + + this.header = new GZheader(); + + zlib_inflate.inflateGetHeader(this.strm, this.header); +} + +/** + * Inflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with + * new output chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the decompression context. + * + * On fail call [[Inflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Inflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var dict; + + // Flag to properly process Z_BUF_ERROR on testing inflate call + // when we check that all output data was flushed. + var allowBufError = false; + + if (this.ended) { return false; } + _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // Only binary strings can be decompressed on practice + strm.input = strings.binstring2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ + + if (status === c.Z_NEED_DICT && dictionary) { + // Convert data if needed + if (typeof dictionary === 'string') { + dict = strings.string2buf(dictionary); + } else if (toString.call(dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(dictionary); + } else { + dict = dictionary; + } + + status = zlib_inflate.inflateSetDictionary(this.strm, dict); + + } + + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { + + if (this.options.to === 'string') { + + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + + // move tail + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } + + this.onData(utf8str); + + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + + // When no more input data, we should check that internal inflate buffers + // are flushed. The only way to do it when avail_out = 0 - run one more + // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. + // Here we set flag to process this error properly. + // + // NOTE. Deflate does not return error in this case and does not needs such + // logic. + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + + // Finalize on the last chunk. + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Inflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Inflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Inflate#onEnd(status) -> Void + * - status (Number): inflate status. 0 (Z_OK) on success, + * other if not. + * + * Called either after you tell inflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Inflate.prototype.onEnd = function (status) { + // On success - join + if (status === c.Z_OK) { + if (this.options.to === 'string') { + // Glue & convert here, until we teach pako to send + // utf8 aligned strings to onData + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * inflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Decompress `data` with inflate/ungzip and `options`. Autodetect + * format via wrapper header by default. That's why we don't provide + * separate `ungzip` method. + * + * Supported options are: + * + * - windowBits + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be converted + * from utf8 to utf16 (javascript) string. When string output requested, + * chunk length can differ from `chunkSize`, depending on content. + * + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) + * , output; + * + * try { + * output = pako.inflate(input); + * } catch (err) + * console.log(err); + * } + * ``` + **/ +function inflate(input, options) { + var inflator = new Inflate(options); + + inflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (inflator.err) { throw inflator.msg || msg[inflator.err]; } + + return inflator.result; +} + + +/** + * inflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * The same as [[inflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); +} + + +/** + * ungzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to decompress. + * - options (Object): zlib inflate options. + * + * Just shortcut to [[inflate]], because it autodetects format + * by header.content. Done for convenience. + **/ + + +exports.Inflate = Inflate; +exports.inflate = inflate; +exports.inflateRaw = inflateRaw; +exports.ungzip = inflate; + + +/***/ }), +/* 142 */ +/*!*********************************************!*\ + !*** ./node_modules/pako/lib/zlib/trees.js ***! + \*********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(/*! ../utils/common */ 45); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + + +/***/ }), +/* 143 */ +/*!***********************************************!*\ + !*** ./node_modules/pako/lib/zlib/deflate.js ***! + \***********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = __webpack_require__(/*! ../utils/common */ 45); +var trees = __webpack_require__(/*! ./trees */ 142); +var adler32 = __webpack_require__(/*! ./adler32 */ 93); +var crc32 = __webpack_require__(/*! ./crc32 */ 92); +var msg = __webpack_require__(/*! ./messages */ 71); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + + +/***/ }), +/* 144 */ +/*!******************************************!*\ + !*** ./node_modules/pako/lib/deflate.js ***! + \******************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + + +var zlib_deflate = __webpack_require__(/*! ./zlib/deflate */ 143); +var utils = __webpack_require__(/*! ./utils/common */ 45); +var strings = __webpack_require__(/*! ./utils/strings */ 91); +var msg = __webpack_require__(/*! ./zlib/messages */ 71); +var ZStream = __webpack_require__(/*! ./zlib/zstream */ 90); + +var toString = Object.prototype.toString; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + +var Z_NO_FLUSH = 0; +var Z_FINISH = 4; + +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_SYNC_FLUSH = 2; + +var Z_DEFAULT_COMPRESSION = -1; + +var Z_DEFAULT_STRATEGY = 0; + +var Z_DEFLATED = 8; + +/* ===========================================================================*/ + + +/** + * class Deflate + * + * Generic JS-style wrapper for zlib calls. If you don't need + * streaming behaviour - use more simple functions: [[deflate]], + * [[deflateRaw]] and [[gzip]]. + **/ + +/* internal + * Deflate.chunks -> Array + * + * Chunks of output data, if [[Deflate#onData]] not overridden. + **/ + +/** + * Deflate.result -> Uint8Array|Array + * + * Compressed result, generated by default [[Deflate#onData]] + * and [[Deflate#onEnd]] handlers. Filled after you push last chunk + * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you + * push a chunk with explicit flush (call [[Deflate#push]] with + * `Z_SYNC_FLUSH` param). + **/ + +/** + * Deflate.err -> Number + * + * Error code after deflate finished. 0 (Z_OK) on success. + * You will not need it in real life, because deflate errors + * are possible only on wrong options or bad `onData` / `onEnd` + * custom handlers. + **/ + +/** + * Deflate.msg -> String + * + * Error message, if [[Deflate.err]] != 0 + **/ + + +/** + * new Deflate(options) + * - options (Object): zlib deflate options. + * + * Creates new deflator instance with specified params. Throws exception + * on bad params. Supported options: + * + * - `level` + * - `windowBits` + * - `memLevel` + * - `strategy` + * - `dictionary` + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Additional options, for internal needs: + * + * - `chunkSize` - size of generated data chunks (16K by default) + * - `raw` (Boolean) - do raw deflate + * - `gzip` (Boolean) - create gzip wrapper + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * - `header` (Object) - custom header for gzip + * - `text` (Boolean) - true if compressed data believed to be text + * - `time` (Number) - modification time, unix timestamp + * - `os` (Number) - operation system code + * - `extra` (Array) - array of bytes with extra data (max 65536) + * - `name` (String) - file name (binary string) + * - `comment` (String) - comment (binary string) + * - `hcrc` (Boolean) - true if header crc should be added + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) + * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); + * + * var deflate = new pako.Deflate({ level: 3}); + * + * deflate.push(chunk1, false); + * deflate.push(chunk2, true); // true -> last chunk + * + * if (deflate.err) { throw new Error(deflate.err); } + * + * console.log(deflate.result); + * ``` + **/ +function Deflate(options) { + if (!(this instanceof Deflate)) return new Deflate(options); + + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: '' + }, options || {}); + + var opt = this.options; + + if (opt.raw && (opt.windowBits > 0)) { + opt.windowBits = -opt.windowBits; + } + + else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { + opt.windowBits += 16; + } + + this.err = 0; // error code, if happens (0 = Z_OK) + this.msg = ''; // error message + this.ended = false; // used to avoid multiple onEnd() calls + this.chunks = []; // chunks of compressed data + + this.strm = new ZStream(); + this.strm.avail_out = 0; + + var status = zlib_deflate.deflateInit2( + this.strm, + opt.level, + opt.method, + opt.windowBits, + opt.memLevel, + opt.strategy + ); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + + if (opt.dictionary) { + var dict; + // Convert data if needed + if (typeof opt.dictionary === 'string') { + // If we need to compress text, change encoding to utf8. + dict = strings.string2buf(opt.dictionary); + } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + + if (status !== Z_OK) { + throw new Error(msg[status]); + } + + this._dict_set = true; + } +} + +/** + * Deflate#push(data[, mode]) -> Boolean + * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be + * converted to utf8 byte sequence. + * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. + * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. + * + * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with + * new compressed chunks. Returns `true` on success. The last data block must have + * mode Z_FINISH (or `true`). That will flush internal pending buffers and call + * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you + * can use mode Z_SYNC_FLUSH, keeping the compression context. + * + * On fail call [[Deflate#onEnd]] with error code and return false. + * + * We strongly recommend to use `Uint8Array` on input for best speed (output + * array format is detected automatically). Also, don't skip last param and always + * use the same type in your code (boolean or number). That will improve JS speed. + * + * For regular `Array`-s make sure all elements are [0..255]. + * + * ##### Example + * + * ```javascript + * push(chunk, false); // push one of data chunks + * ... + * push(chunk, true); // push last chunk + * ``` + **/ +Deflate.prototype.push = function (data, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + + if (this.ended) { return false; } + + _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); + + // Convert data if needed + if (typeof data === 'string') { + // If we need to compress text, change encoding to utf8. + strm.input = strings.string2buf(data); + } else if (toString.call(data) === '[object ArrayBuffer]') { + strm.input = new Uint8Array(data); + } else { + strm.input = data; + } + + strm.next_in = 0; + strm.avail_in = strm.input.length; + + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ + + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { + if (this.options.to === 'string') { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + + // Finalize on the last chunk. + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + + // callback interim results if Z_SYNC_FLUSH. + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + + return true; +}; + + +/** + * Deflate#onData(chunk) -> Void + * - chunk (Uint8Array|Array|String): output data. Type of array depends + * on js engine support. When string output requested, each chunk + * will be string. + * + * By default, stores data blocks in `chunks[]` property and glue + * those in `onEnd`. Override this handler, if you need another behaviour. + **/ +Deflate.prototype.onData = function (chunk) { + this.chunks.push(chunk); +}; + + +/** + * Deflate#onEnd(status) -> Void + * - status (Number): deflate status. 0 (Z_OK) on success, + * other if not. + * + * Called once after you tell deflate that the input stream is + * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) + * or if an error happened. By default - join collected chunks, + * free memory and fill `results` / `err` properties. + **/ +Deflate.prototype.onEnd = function (status) { + // On success - join + if (status === Z_OK) { + if (this.options.to === 'string') { + this.result = this.chunks.join(''); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; +}; + + +/** + * deflate(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * Compress `data` with deflate algorithm and `options`. + * + * Supported options are: + * + * - level + * - windowBits + * - memLevel + * - strategy + * - dictionary + * + * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) + * for more information on these. + * + * Sugar (options): + * + * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify + * negative windowBits implicitly. + * - `to` (String) - if equal to 'string', then result will be "binary string" + * (each char code [0..255]) + * + * ##### Example: + * + * ```javascript + * var pako = require('pako') + * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); + * + * console.log(pako.deflate(data)); + * ``` + **/ +function deflate(input, options) { + var deflator = new Deflate(options); + + deflator.push(input, true); + + // That will never happens, if you don't cheat with options :) + if (deflator.err) { throw deflator.msg || msg[deflator.err]; } + + return deflator.result; +} + + +/** + * deflateRaw(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but creates raw data, without wrapper + * (header and adler32 crc). + **/ +function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); +} + + +/** + * gzip(data[, options]) -> Uint8Array|Array|String + * - data (Uint8Array|Array|String): input data to compress. + * - options (Object): zlib deflate options. + * + * The same as [[deflate]], but create gzip wrapper instead of + * deflate one. + **/ +function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); +} + + +exports.Deflate = Deflate; +exports.deflate = deflate; +exports.deflateRaw = deflateRaw; +exports.gzip = gzip; + + +/***/ }), +/* 145 */ +/*!************************************!*\ + !*** ./node_modules/pako/index.js ***! + \************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Top level file is just a mixin of submodules & constants + + +var assign = __webpack_require__(/*! ./lib/utils/common */ 45).assign; + +var deflate = __webpack_require__(/*! ./lib/deflate */ 144); +var inflate = __webpack_require__(/*! ./lib/inflate */ 141); +var constants = __webpack_require__(/*! ./lib/zlib/constants */ 89); + +var pako = {}; + +assign(pako, deflate, inflate, constants); + +module.exports = pako; + + +/***/ }), +/* 146 */ +/*!*****************************************!*\ + !*** ./node_modules/jszip/lib/flate.js ***! + \*****************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined'); + +var pako = __webpack_require__(/*! pako */ 145); +var utils = __webpack_require__(/*! ./utils */ 28); +var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 34); + +var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + +exports.magic = "\x08\x00"; + +/** + * Create a worker that uses pako to inflate/deflate. + * @constructor + * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate". + * @param {Object} options the options to use when (de)compressing. + */ +function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + // the `meta` object from the last chunk received + // this allow this worker to pass around metadata + this.meta = {}; +} + +utils.inherits(FlateWorker, GenericWorker); + +/** + * @see GenericWorker.processChunk + */ +FlateWorker.prototype.processChunk = function (chunk) { + this.meta = chunk.meta; + if (this._pako === null) { + this._createPako(); + } + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); +}; + +/** + * @see GenericWorker.flush + */ +FlateWorker.prototype.flush = function () { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) { + this._createPako(); + } + this._pako.push([], true); +}; +/** + * @see GenericWorker.cleanUp + */ +FlateWorker.prototype.cleanUp = function () { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; +}; + +/** + * Create the _pako object. + * TODO: lazy-loading this object isn't the best solution but it's the + * quickest. The best solution is to lazy-load the worker list. See also the + * issue #446. + */ +FlateWorker.prototype._createPako = function () { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 // default compression + }); + var self = this; + this._pako.onData = function(data) { + self.push({ + data : data, + meta : self.meta + }); + }; +}; + +exports.compressWorker = function (compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); +}; +exports.uncompressWorker = function () { + return new FlateWorker("Inflate", {}); +}; + + +/***/ }), +/* 147 */ +/*!**************************************************!*\ + !*** ./node_modules/jszip/lib/generate/index.js ***! + \**************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var compressions = __webpack_require__(/*! ../compressions */ 94); +var ZipFileWorker = __webpack_require__(/*! ./ZipFileWorker */ 136); + +/** + * Find the compression to use. + * @param {String} fileCompression the compression defined at the file level, if any. + * @param {String} zipCompression the compression defined at the load() level. + * @return {Object} the compression object to use. + */ +var getCompression = function (fileCompression, zipCompression) { + + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) { + throw new Error(compressionName + " is not a valid compression method !"); + } + return compression; +}; + +/** + * Create a worker to generate a zip file. + * @param {JSZip} zip the JSZip instance at the right root level. + * @param {Object} options to generate the zip file. + * @param {String} comment the comment to use. + */ +exports.generateWorker = function (zip, options, comment) { + + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + + zip.forEach(function (relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var dir = file.dir, date = file.date; + + file._compressWorker(compression, compressionOptions) + .withStreamInfo("file", { + name : relativePath, + dir : dir, + date : date, + comment : file.comment || "", + unixPermissions : file.unixPermissions, + dosPermissions : file.dosPermissions + }) + .pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + + return zipFileWorker; +}; + + +/***/ }), +/* 148 */ +/*!*********************************************!*\ + !*** ./node_modules/jszip/lib/zipObject.js ***! + \*********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var StreamHelper = __webpack_require__(/*! ./stream/StreamHelper */ 99); +var DataWorker = __webpack_require__(/*! ./stream/DataWorker */ 97); +var utf8 = __webpack_require__(/*! ./utf8 */ 52); +var CompressedObject = __webpack_require__(/*! ./compressedObject */ 73); +var GenericWorker = __webpack_require__(/*! ./stream/GenericWorker */ 34); + +/** + * A simple object representing a file in the zip file. + * @constructor + * @param {string} name the name of the file + * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data + * @param {Object} options the options of the file + */ +var ZipObject = function(name, data, options) { + this.name = name; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + + this._data = data; + this._dataBinary = options.binary; + // keep only the compression + this.options = { + compression : options.compression, + compressionOptions : options.compressionOptions + }; +}; + +ZipObject.prototype = { + /** + * Create an internal stream for the content of this object. + * @param {String} type the type of each chunk. + * @return StreamHelper the stream. + */ + internalStream: function (type) { + var result = null, outputType = "string"; + try { + if (!type) { + throw new Error("No output type specified."); + } + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") { + outputType = "string"; + } + result = this._decompressWorker(); + + var isUnicodeString = !this._dataBinary; + + if (isUnicodeString && !askUnicodeString) { + result = result.pipe(new utf8.Utf8EncodeWorker()); + } + if (!isUnicodeString && askUnicodeString) { + result = result.pipe(new utf8.Utf8DecodeWorker()); + } + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + + return new StreamHelper(result, outputType, ""); + }, + + /** + * Prepare the content in the asked type. + * @param {String} type the type of the result. + * @param {Function} onUpdate a function to call on each internal update. + * @return Promise the promise of the result. + */ + async: function (type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + + /** + * Prepare the content as a nodejs stream. + * @param {String} type the type of each chunk. + * @param {Function} onUpdate a function to call on each internal update. + * @return Stream the stream. + */ + nodeStream: function (type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + + /** + * Return a worker for the compressed content. + * @private + * @param {Object} compression the compression object to use. + * @param {Object} compressionOptions the options to use when compressing. + * @return Worker the worker. + */ + _compressWorker: function (compression, compressionOptions) { + if ( + this._data instanceof CompressedObject && + this._data.compression.magic === compression.magic + ) { + return this._data.getCompressedWorker(); + } else { + var result = this._decompressWorker(); + if(!this._dataBinary) { + result = result.pipe(new utf8.Utf8EncodeWorker()); + } + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + /** + * Return a worker for the decompressed content. + * @private + * @return Worker the worker. + */ + _decompressWorker : function () { + if (this._data instanceof CompressedObject) { + return this._data.getContentWorker(); + } else if (this._data instanceof GenericWorker) { + return this._data; + } else { + return new DataWorker(this._data); + } + } +}; + +var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; +var removedFn = function () { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); +}; + +for(var i = 0; i < removedMethods.length; i++) { + ZipObject.prototype[removedMethods[i]] = removedFn; +} +module.exports = ZipObject; + + +/***/ }), +/* 149 */ +/*!********************************************************************!*\ + !*** ./node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js ***! + \********************************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Readable = __webpack_require__(/*! readable-stream */ 110).Readable; + +var utils = __webpack_require__(/*! ../utils */ 28); +utils.inherits(NodejsStreamOutputAdapter, Readable); + +/** +* A nodejs stream using a worker as source. +* @see the SourceWrapper in http://nodejs.org/api/stream.html +* @constructor +* @param {StreamHelper} helper the helper wrapping the worker +* @param {Object} options the nodejs stream options +* @param {Function} updateCb the update callback. +*/ +function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + + var self = this; + helper.on("data", function (data, meta) { + if (!self.push(data)) { + self._helper.pause(); + } + if(updateCb) { + updateCb(meta); + } + }) + .on("error", function(e) { + self.emit('error', e); + }) + .on("end", function () { + self.push(null); + }); +} + + +NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); +}; + +module.exports = NodejsStreamOutputAdapter; + + +/***/ }), +/* 150 */ +/*!********************************************************!*\ + !*** ./node_modules/jszip/lib/stream/ConvertWorker.js ***! + \********************************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var GenericWorker = __webpack_require__(/*! ./GenericWorker */ 34); +var utils = __webpack_require__(/*! ../utils */ 28); + +/** + * A worker which convert chunks to a specified type. + * @constructor + * @param {String} destType the destination type. + */ +function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; +} +utils.inherits(ConvertWorker, GenericWorker); + +/** + * @see GenericWorker.processChunk + */ +ConvertWorker.prototype.processChunk = function (chunk) { + this.push({ + data : utils.transformTo(this.destType, chunk.data), + meta : chunk.meta + }); +}; +module.exports = ConvertWorker; + + +/***/ }), +/* 151 */ +/*!***********************************************!*\ + !*** ./node_modules/immediate/lib/browser.js ***! + \***********************************************/ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var Mutation = global.MutationObserver || global.WebKitMutationObserver; + +var scheduleDrain; + +{ + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global.document.createTextNode(''); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function () { + element.data = (called = ++called % 2); + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { + var channel = new global.MessageChannel(); + channel.port1.onmessage = nextTick; + scheduleDrain = function () { + channel.port2.postMessage(0); + }; + } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { + scheduleDrain = function () { + + // Create a