/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 5);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!***********************!*\
!*** ./src/Player.js ***!
\***********************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__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 */ 15);
/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./BitNode.js */ 13);
/* 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 */ 39);
/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./CreateProgram.js */ 20);
/* 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 */ 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 */ 26);
/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Server.js */ 11);
/* 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 */ 38);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! decimal.js */ 19);
/* 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 */ 14);
/* 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__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__);
function PlayerObject() {
//Skills and stats
this.hacking_skill = 1;
//Combat stats
this.hp = 10;
this.max_hp = 10;
this.strength = 1; //Damage dealt
this.defense = 1; //Damage received
this.dexterity = 1; //Accuracy
this.agility = 1; //Dodge %
//Labor stats
this.charisma = 1;
//Special stats
this.intelligence = 0;
//Hacking multipliers
this.hacking_chance_mult = 1;
this.hacking_speed_mult = 1;
this.hacking_money_mult = 1;
this.hacking_grow_mult = 1;
//Experience and multipliers
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.intelligence_exp= 0;
this.hacking_mult = 1;
this.strength_mult = 1;
this.defense_mult = 1;
this.dexterity_mult = 1;
this.agility_mult = 1;
this.charisma_mult = 1;
this.hacking_exp_mult = 1;
this.strength_exp_mult = 1;
this.defense_exp_mult = 1;
this.dexterity_exp_mult = 1;
this.agility_exp_mult = 1;
this.charisma_exp_mult = 1;
this.company_rep_mult = 1;
this.faction_rep_mult = 1;
//Money
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000);
this.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](0); //Total money ever earned in this "simulation"
this.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](0); //Total money ever earned
//IP Address of Starting (home) computer
this.homeComputer = "";
//Location information
this.city = _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12;
this.location = "";
//Company Information
this.companyName = ""; //Name of Company, equivalent to an object from Locations
this.companyPosition = ""; //CompanyPosition object
//Servers
this.currentServer = ""; //IP address of Server currently being accessed through terminal
this.purchasedServers = []; //IP Addresses of purchased servers
this.hacknetNodes = [];
this.hacknetNodeWrappers = [];
this.totalHacknetNodeProduction = 0;
//Factions
this.factions = []; //Names of all factions player has joined
this.factionInvitations = []; //Outstanding faction invitations
//Augmentations
this.queuedAugmentations = [];
this.augmentations = [];
this.sourceFiles = [];
//Crime statistics
this.numPeopleKilled = 0;
this.karma = 0;
this.crime_money_mult = 1;
this.crime_success_mult = 1;
//Flag to let the engine know the player is starting an action
// Current actions: hack, analyze
this.startAction = false;
this.actionTime = 0;
//Flags/variables for working (Company, Faction, Creating Program, Taking Class)
this.isWorking = false;
this.workType = "";
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workMoneyLossRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.createProgramName = "";
this.createProgramReqLvl = 0;
this.className = "";
this.crimeType = "";
this.timeWorked = 0; //in ms
this.timeWorkedCreateProgram = 0;
this.timeNeededToCompleteWork = 0;
this.work_money_mult = 1;
//Hacknet Node multipliers
this.hacknet_node_money_mult = 1;
this.hacknet_node_purchase_cost_mult = 1;
this.hacknet_node_ram_cost_mult = 1;
this.hacknet_node_core_cost_mult = 1;
this.hacknet_node_level_cost_mult = 1;
//Stock Market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
//Gang
this.gang = 0;
//Corporation
this.corporation = 0;
//Bladeburner
this.bladeburner = 0;
this.bladeburner_max_stamina_mult = 1;
this.bladeburner_stamina_gain_mult = 1;
this.bladeburner_analysis_mult = 1; //Field Analysis Only
this.bladeburner_success_chance_mult = 1;
//bitnode
this.bitNodeN = 1;
//Flags for determining whether certain "thresholds" have been achieved
this.firstFacInvRecvd = false;
this.firstAugPurchased = false;
this.firstJobRecvd = false;
this.firstTimeTraveled = false;
this.firstProgramAvailable = false;
//Used to store the last update time.
this.lastUpdate = 0;
this.totalPlaytime = 0;
this.playtimeSinceLastAug = 0;
this.playtimeSinceLastBitnode = 0;
//Production since last Augmentation installation
this.scriptProdSinceLastAug = 0;
this.stockProdSinceLastAug = 0;
this.crimeProdSinceLastAug = 0;
this.jobProdSinceLastAug = 0;
};
PlayerObject.prototype.init = function() {
/* Initialize Player's home computer */
var t_homeComp = new _Server_js__WEBPACK_IMPORTED_MODULE_12__["Server"]({
ip:Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_18__["createRandomIp"])(), hostname:"home", organizationName:"Home PC",
isConnectedTo:true, adminRights:true, purchasedByPlayer:true, maxRam:8
});
this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
Object(_Server_js__WEBPACK_IMPORTED_MODULE_12__["AddToAllServers"])(t_homeComp);
this.getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_5__["Programs"].NukeProgram.name);
}
PlayerObject.prototype.prestigeAugmentation = function() {
var homeComp = this.getHomeComputer();
this.currentServer = homeComp.ip;
this.homeComputer = homeComp.ip;
this.numPeopleKilled = 0;
this.karma = 0;
//Reset stats
this.hacking_skill = 1;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
this.charisma = 1;
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000);
this.city = _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.startAction = false;
this.actionTime = 0;
this.isWorking = false;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
this.crimeType = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.lastUpdate = new Date().getTime();
this.playtimeSinceLastAug = 0;
this.scriptProdSinceLastAug = 0;
this.hacknetNodes.length = 0;
this.totalHacknetNodeProduction = 0;
}
PlayerObject.prototype.prestigeSourceFile = function() {
var homeComp = this.getHomeComputer();
this.currentServer = homeComp.ip;
this.homeComputer = homeComp.ip;
this.numPeopleKilled = 0;
this.karma = 0;
//Reset stats
this.hacking_skill = 1;
this.strength = 1;
this.defense = 1;
this.dexterity = 1;
this.agility = 1;
this.charisma = 1;
this.hacking_exp = 0;
this.strength_exp = 0;
this.defense_exp = 0;
this.dexterity_exp = 0;
this.agility_exp = 0;
this.charisma_exp = 0;
this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](1000);
this.city = _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.purchasedServers = [];
this.factions = [];
this.factionInvitations = [];
this.queuedAugmentations = [];
this.augmentations = [];
this.startAction = false;
this.actionTime = 0;
this.isWorking = false;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
this.crimeType = "";
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.lastUpdate = new Date().getTime();
this.hacknetNodes.length = 0;
this.totalHacknetNodeProduction = 0;
//Gang
this.gang = null;
Object(_Gang_js__WEBPACK_IMPORTED_MODULE_9__["resetGangs"])();
//Reset Stock market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
//BitNode 3: Corporatocracy
if (this.bitNodeN === 3) {this.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](150e9);}
this.corporation = 0;
this.playtimeSinceLastAug = 0;
this.playtimeSinceLastBitnode = 0;
this.scriptProdSinceLastAug = 0;
}
PlayerObject.prototype.getCurrentServer = function() {
return _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][this.currentServer];
}
PlayerObject.prototype.getHomeComputer = function() {
return _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][this.homeComputer];
}
PlayerObject.prototype.getUpgradeHomeRamCost = function() {
//Calculate how many times ram has been upgraded (doubled)
const currentRam = Player.getHomeComputer().maxRam;
const numUpgrades = Math.log2(currentRam);
//Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded
const mult = Math.pow(1.58, numUpgrades);
var cost = currentRam * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].BaseCostFor1GBOfRamHome * mult;
return cost;
}
PlayerObject.prototype.receiveInvite = function(factionName) {
if(this.factionInvitations.includes(factionName) || this.factions.includes(factionName)) {
return;
}
this.firstFacInvRecvd = true;
this.factionInvitations.push(factionName);
}
//Calculates skill level based on experience. The same formula will be used for every skill
PlayerObject.prototype.calculateSkill = function(exp, mult=1) {
return Math.max(Math.floor(mult*(32 * Math.log(exp + 534.5) - 200)), 1);
}
PlayerObject.prototype.updateSkillLevels = function() {
this.hacking_skill = Math.max(1, Math.floor(this.calculateSkill(this.hacking_exp, this.hacking_mult) * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackingLevelMultiplier));
this.strength = this.calculateSkill(this.strength_exp, this.strength_mult);
this.defense = this.calculateSkill(this.defense_exp, this.defense_mult);
this.dexterity = this.calculateSkill(this.dexterity_exp, this.dexterity_mult);
this.agility = this.calculateSkill(this.agility_exp, this.agility_mult);
this.charisma = this.calculateSkill(this.charisma_exp, this.charisma_mult);
if (this.intelligence > 0) {
this.intelligence = Math.floor(this.calculateSkill(this.intelligence_exp));
} else {
this.intelligence = 0;
}
var ratio = this.hp / this.max_hp;
this.max_hp = Math.floor(10 + this.defense / 10);
Player.hp = Math.round(this.max_hp * ratio);
}
PlayerObject.prototype.resetMultipliers = function() {
this.hacking_chance_mult = 1;
this.hacking_speed_mult = 1;
this.hacking_money_mult = 1;
this.hacking_grow_mult = 1;
this.hacking_mult = 1;
this.strength_mult = 1;
this.defense_mult = 1;
this.dexterity_mult = 1;
this.agility_mult = 1;
this.charisma_mult = 1;
this.hacking_exp_mult = 1;
this.strength_exp_mult = 1;
this.defense_exp_mult = 1;
this.dexterity_exp_mult = 1;
this.agility_exp_mult = 1;
this.charisma_exp_mult = 1;
this.company_rep_mult = 1;
this.faction_rep_mult = 1;
this.crime_money_mult = 1;
this.crime_success_mult = 1;
this.hacknet_node_money_mult = 1;
this.hacknet_node_purchase_cost_mult = 1;
this.hacknet_node_ram_cost_mult = 1;
this.hacknet_node_core_cost_mult = 1;
this.hacknet_node_level_cost_mult = 1;
this.work_money_mult = 1;
this.bladeburner_max_stamina_mult = 1;
this.bladeburner_stamina_gain_mult = 1;
this.bladeburner_analysis_mult = 1;
this.bladeburner_success_chance_mult = 1;
}
//Calculates the chance of hacking a server
//The formula is:
// (2 * hacking_chance_multiplier * hacking_skill - requiredLevel) 100 - difficulty
// ----------------------------------------------------------- * -----------------
// (2 * hacking_chance_multiplier * hacking_skill) 100
PlayerObject.prototype.calculateHackingChance = function() {
var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100;
var skillMult = (1.75 * this.hacking_skill) + (0.2 * this.intelligence);
var skillChance = (skillMult - this.getCurrentServer().requiredHackingSkill) / skillMult;
var chance = skillChance * difficultyMult * this.hacking_chance_mult;
if (chance > 1) {return 1;}
if (chance < 0) {return 0;}
return chance;
}
//Calculate the time it takes to hack a server in seconds. Returns the time
//The formula is:
// (2.5 * requiredLevel * difficulty + 200)
// ----------------------------------- * hacking_speed_multiplier
// hacking_skill + 100
PlayerObject.prototype.calculateHackingTime = function() {
var difficultyMult = this.getCurrentServer().requiredHackingSkill * this.getCurrentServer().hackDifficulty;
var skillFactor = (2.5 * difficultyMult + 200) / (this.hacking_skill + 100 + (0.1 * this.intelligence));
return 5 * skillFactor / this.hacking_speed_mult;
}
//Calculates the PERCENTAGE of a server's money that the player will hack from the server if successful
//The formula is:
// (hacking_skill - (requiredLevel-1)) 100 - difficulty
// --------------------------------------* ----------------------- * hacking_money_multiplier
// hacking_skill 100
PlayerObject.prototype.calculatePercentMoneyHacked = function() {
var difficultyMult = (100 - this.getCurrentServer().hackDifficulty) / 100;
var skillMult = (this.hacking_skill - (this.getCurrentServer().requiredHackingSkill - 1)) / this.hacking_skill;
var percentMoneyHacked = difficultyMult * skillMult * this.hacking_money_mult / 240;
console.log("Percent money hacked calculated to be: " + percentMoneyHacked);
if (percentMoneyHacked < 0) {return 0;}
if (percentMoneyHacked > 1) {return 1;}
return percentMoneyHacked * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ManualHackMoney;
}
//Returns how much EXP the player gains on a successful hack
//The formula is:
// difficulty * requiredLevel * hacking_multiplier
PlayerObject.prototype.calculateExpGain = function() {
var s = this.getCurrentServer();
if (s.baseDifficulty == null) {
s.baseDifficulty = s.hackDifficulty;
}
return (s.baseDifficulty * this.hacking_exp_mult * 0.3 + 3) * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].HackExpGain;
}
//Hack/Analyze a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for
//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the
//required hacking skill and that the player has admin rights.
PlayerObject.prototype.hack = function() {
this.actionTime = this.calculateHackingTime();
console.log("Hacking time: " + this.actionTime);
this.startAction = true; //Set the startAction flag so the engine starts the hacking process
}
PlayerObject.prototype.analyze = function() {
this.actionTime = 1;
this.startAction = true;
}
PlayerObject.prototype.hasProgram = function(programName) {
var home = Player.getHomeComputer();
for (var i = 0; i < home.programs.length; ++i) {
if (programName.toLowerCase() == home.programs[i].toLowerCase()) {return true;}
}
return false;
}
PlayerObject.prototype.setMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.setMoney()"); return;
}
this.money = money;
}
PlayerObject.prototype.gainMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.gainMoney()"); return;
}
this.money = this.money.plus(money);
this.total_money = this.total_money.plus(money);
this.lifetime_money = this.lifetime_money.plus(money);
}
PlayerObject.prototype.loseMoney = function(money) {
if (isNaN(money)) {
console.log("ERR: NaN passed into Player.loseMoney()"); return;
}
this.money = this.money.minus(money);
}
PlayerObject.prototype.gainHackingExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainHackingExp()"); return;
}
this.hacking_exp += exp;
if(this.hacking_exp < 0) {
this.hacking_exp = 0;
}
}
PlayerObject.prototype.gainStrengthExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainStrengthExp()"); return;
}
this.strength_exp += exp;
if(this.strength_exp < 0) {
this.strength_exp = 0;
}
}
PlayerObject.prototype.gainDefenseExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into player.gainDefenseExp()"); return;
}
this.defense_exp += exp;
if(this.defense_exp < 0) {
this.defense_exp = 0;
}
}
PlayerObject.prototype.gainDexterityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainDexterityExp()"); return;
}
this.dexterity_exp += exp;
if(this.dexterity_exp < 0) {
this.dexterity_exp = 0;
}
}
PlayerObject.prototype.gainAgilityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainAgilityExp()"); return;
}
this.agility_exp += exp;
if(this.agility_exp < 0) {
this.agility_exp = 0;
}
}
PlayerObject.prototype.gainCharismaExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainCharismaExp()"); return;
}
this.charisma_exp += exp;
if(this.charisma_exp < 0) {
this.charisma_exp = 0;
}
}
PlayerObject.prototype.gainIntelligenceExp = function(exp) {
if (isNaN(exp)) {
console.log("ERROR: NaN passed into Player.gainIntelligenceExp()"); return;
}
if (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__["hasAISF"] || this.intelligence > 0) {
this.intelligence_exp += exp;
} else {
console.log("Not gaining intelligence experience bc it hasn't been unlocked yet");
}
}
//Given a string expression like "str" or "strength", returns the given stat
PlayerObject.prototype.queryStatFromString = function(str) {
var tempStr = str.toLowerCase();
if (tempStr.includes("hack")) {return Player.hacking_skill;}
if (tempStr.includes("str")) {return Player.strength;}
if (tempStr.includes("def")) {return Player.defense;}
if (tempStr.includes("dex")) {return Player.dexterity;}
if (tempStr.includes("agi")) {return Player.agility;}
if (tempStr.includes("cha")) {return Player.charisma;}
if (tempStr.includes("int")) {return Player.intelligence;}
}
/******* Working functions *******/
PlayerObject.prototype.resetWorkStatus = function() {
this.workHackExpGainRate = 0;
this.workStrExpGainRate = 0;
this.workDefExpGainRate = 0;
this.workDexExpGainRate = 0;
this.workAgiExpGainRate = 0;
this.workChaExpGainRate = 0;
this.workRepGainRate = 0;
this.workMoneyGainRate = 0;
this.workHackExpGained = 0;
this.workStrExpGained = 0;
this.workDefExpGained = 0;
this.workDexExpGained = 0;
this.workAgiExpGained = 0;
this.workChaExpGained = 0;
this.workRepGained = 0;
this.workMoneyGained = 0;
this.timeWorked = 0;
this.timeWorkedCreateProgram = 0;
this.currentWorkFactionName = "";
this.currentWorkFactionDescription = "";
this.createProgramName = "";
this.className = "";
document.getElementById("work-in-progress-text").innerHTML = "";
}
PlayerObject.prototype.gainWorkExp = function() {
this.gainHackingExp(this.workHackExpGained);
this.gainStrengthExp(this.workStrExpGained);
this.gainDefenseExp(this.workDefExpGained);
this.gainDexterityExp(this.workDexExpGained);
this.gainAgilityExp(this.workAgiExpGained);
this.gainCharismaExp(this.workChaExpGained);
}
/* Working for Company */
PlayerObject.prototype.finishWork = function(cancelled, sing=false) {
//Since the work was cancelled early, player only gains half of what they've earned so far
if (cancelled) {
this.workRepGained /= 2;
}
this.gainWorkExp();
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
company.playerReputation += (this.workRepGained);
this.gainMoney(this.workMoneyGained);
this.updateSkillLevels();
var txt = "You earned a total of:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation for the company
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
";
if (cancelled) {
txt = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"Since you cancelled your work early, you only gained half of the reputation you earned.
" + txt;
} else {
txt = "You worked a full shift of 8 hours!
" + txt;
}
if (!sing) {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
if (sing) {
var res = "You worked a short shift of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " +
"earned $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + ", " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp, and " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
PlayerObject.prototype.startWork = function() {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompany;
this.workHackExpGainRate = this.getWorkHackExpGain();
this.workStrExpGainRate = this.getWorkStrExpGain();
this.workDefExpGainRate = this.getWorkDefExpGain();
this.workDexExpGainRate = this.getWorkDexExpGain();
this.workAgiExpGainRate = this.getWorkAgiExpGain();
this.workChaExpGainRate = this.getWorkChaExpGain();
this.workRepGainRate = this.getWorkRepGain();
this.workMoneyGainRate = this.getWorkMoneyGain();
this.timeNeededToCompleteWork = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Cancel Work";
newCancelButton.addEventListener("click", function() {
Player.finishWork(true);
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.work = function(numCycles) {
this.workRepGainRate = this.getWorkRepGain();
this.workHackExpGained += this.workHackExpGainRate * numCycles;
this.workStrExpGained += this.workStrExpGainRate * numCycles;
this.workDefExpGained += this.workDefExpGainRate * numCycles;
this.workDexExpGained += this.workDexExpGainRate * numCycles;
this.workAgiExpGained += this.workAgiExpGainRate * numCycles;
this.workChaExpGained += this.workChaExpGainRate * numCycles;
this.workRepGained += this.workRepGainRate * numCycles;
this.workMoneyGained += this.workMoneyGainRate * numCycles;
var cyclesPerSec = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed;
this.timeWorked += _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (this.timeWorked >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours) {
var maxCycles = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer8Hours;
this.workHackExpGained = this.workHackExpGainRate * maxCycles;
this.workStrExpGained = this.workStrExpGainRate * maxCycles;
this.workDefExpGained = this.workDefExpGainRate * maxCycles;
this.workDexExpGained = this.workDexExpGainRate * maxCycles;
this.workAgiExpGained = this.workAgiExpGainRate * maxCycles;
this.workChaExpGained = this.workChaExpGainRate * maxCycles;
this.workRepGained = this.workRepGainRate * maxCycles;
this.workMoneyGained = this.workMoneyGainRate * maxCycles;
this.finishWork(false);
return;
}
var comp = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName], companyRep = "0";
if (comp == null || !(comp instanceof _Company_js__WEBPACK_IMPORTED_MODULE_2__["Company"])) {
console.log("ERROR: Could not find Company: " + this.companyName);
} else {
companyRep = comp.playerReputation;
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName +
" at " + this.companyName + " (Current Company Reputation: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(companyRep, 0) + ")
" +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"You have earned:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp
" +
"You will automatically finish after working for 8 hours. You can cancel earlier if you wish, " +
"but you will only gain half of the reputation you've earned so far."
}
PlayerObject.prototype.startWorkPartTime = function() {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompanyPartTime;
this.workHackExpGainRate = this.getWorkHackExpGain();
this.workStrExpGainRate = this.getWorkStrExpGain();
this.workDefExpGainRate = this.getWorkDefExpGain();
this.workDexExpGainRate = this.getWorkDexExpGain();
this.workAgiExpGainRate = this.getWorkAgiExpGain();
this.workChaExpGainRate = this.getWorkChaExpGain();
this.workRepGainRate = this.getWorkRepGain();
this.workMoneyGainRate = this.getWorkMoneyGain();
this.timeNeededToCompleteWork = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours;
var newCancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Stop Working";
newCancelButton.addEventListener("click", function() {
Player.finishWorkPartTime();
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.workPartTime = function(numCycles) {
this.workRepGainRate = this.getWorkRepGain();
this.workHackExpGained += this.workHackExpGainRate * numCycles;
this.workStrExpGained += this.workStrExpGainRate * numCycles;
this.workDefExpGained += this.workDefExpGainRate * numCycles;
this.workDexExpGained += this.workDexExpGainRate * numCycles;
this.workAgiExpGained += this.workAgiExpGainRate * numCycles;
this.workChaExpGained += this.workChaExpGainRate * numCycles;
this.workRepGained += this.workRepGainRate * numCycles;
this.workMoneyGained += this.workMoneyGainRate * numCycles;
var cyclesPerSec = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed;
this.timeWorked += _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (this.timeWorked >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer8Hours) {
var maxCycles = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer8Hours;
this.workHackExpGained = this.workHackExpGainRate * maxCycles;
this.workStrExpGained = this.workStrExpGainRate * maxCycles;
this.workDefExpGained = this.workDefExpGainRate * maxCycles;
this.workDexExpGained = this.workDexExpGainRate * maxCycles;
this.workAgiExpGained = this.workAgiExpGainRate * maxCycles;
this.workChaExpGained = this.workChaExpGainRate * maxCycles;
this.workRepGained = this.workRepGainRate * maxCycles;
this.workMoneyGained = this.workMoneyGainRate * maxCycles;
this.finishWorkPartTime();
return;
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName +
" at " + Player.companyName + "
" +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"You have earned:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp
" +
"You will automatically finish after working for 8 hours. You can cancel earlier if you wish,
" +
"and there will be no penalty because this is a part-time job.";
}
PlayerObject.prototype.finishWorkPartTime = function(sing=false) {
this.gainWorkExp();
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
company.playerReputation += (this.workRepGained);
this.gainMoney(this.workMoneyGained);
this.updateSkillLevels();
var txt = "You earned a total of:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation for the company
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
";
txt = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" + txt;
if (!sing) {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
if (sing) {
var res = "You worked for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + " and " +
"earned a total of " +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + ", " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp, and " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
/* Working for Faction */
PlayerObject.prototype.finishFactionWork = function(cancelled, sing=false) {
this.gainWorkExp();
var faction = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"][this.currentWorkFactionName];
faction.playerReputation += (this.workRepGained);
this.gainMoney(this.workMoneyGained);
this.updateSkillLevels();
var txt = "You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"You earned a total of:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " reputation for the faction
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
";
if (!sing) {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadFactionContent();
Object(_Faction_js__WEBPACK_IMPORTED_MODULE_8__["displayFactionContent"])(faction.name);
if (sing) {
var res="You worked for your faction " + faction.name + " for a total of " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ". " +
"You earned " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " rep, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " str exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " def exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dex exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agi exp, and " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " cha exp.";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
PlayerObject.prototype.startFactionWork = function(faction) {
//Update reputation gain rate to account for faction favor
var favorMult = 1 + (faction.favor / 100);
if (isNaN(favorMult)) {favorMult = 1;}
this.workRepGainRate *= favorMult;
this.workRepGainRate *= _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain;
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeFaction;
this.currentWorkFactionName = faction.name;
this.timeNeededToCompleteWork = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours;
var cancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Stop Faction Work";
cancelButton.addEventListener("click", function() {
Player.finishFactionWork(true);
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.startFactionHackWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = .15 * this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult;
this.factionWorkType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkHacking;
this.currentWorkFactionDescription = "carrying out hacking contracts";
this.startFactionWork(faction);
}
PlayerObject.prototype.startFactionFieldWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = .1 * this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = .1 * this.strength_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = .1 * this.defense_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = .1 * this.dexterity_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = .1 * this.agility_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = .1 * this.charisma_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.getFactionFieldWorkRepGain();
this.factionWorkType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkField;
this.currentWorkFactionDescription = "carrying out field missions"
this.startFactionWork(faction);
}
PlayerObject.prototype.startFactionSecurityWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = 0.05 * this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workStrExpGainRate = 0.15 * this.strength_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDefExpGainRate = 0.15 * this.defense_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkExpGain;
this.workRepGainRate = this.getFactionSecurityWorkRepGain();
this.factionWorkType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkSecurity;
this.currentWorkFactionDescription = "performing security detail"
this.startFactionWork(faction);
}
PlayerObject.prototype.workForFaction = function(numCycles) {
var faction = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"][this.currentWorkFactionName];
//Constantly update the rep gain rate
switch (this.factionWorkType) {
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkHacking:
this.workRepGainRate = (this.hacking_skill + this.intelligence) / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel * this.faction_rep_mult;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkField:
this.workRepGainRate = this.getFactionFieldWorkRepGain();
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].FactionWorkSecurity:
this.workRepGainRate = this.getFactionSecurityWorkRepGain();
break;
default:
break;
}
//Update reputation gain rate to account for faction favor
var favorMult = 1 + (faction.favor / 100);
if (isNaN(favorMult)) {favorMult = 1;}
this.workRepGainRate *= favorMult;
this.workRepGainRate *= _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].FactionWorkRepGain;
this.workHackExpGained += this.workHackExpGainRate * numCycles;
this.workStrExpGained += this.workStrExpGainRate * numCycles;
this.workDefExpGained += this.workDefExpGainRate * numCycles;
this.workDexExpGained += this.workDexExpGainRate * numCycles;
this.workAgiExpGained += this.workAgiExpGainRate * numCycles;
this.workChaExpGained += this.workChaExpGainRate * numCycles;
this.workRepGained += this.workRepGainRate * numCycles;
this.workMoneyGained += this.workMoneyGainRate * numCycles;
var cyclesPerSec = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed;
this.timeWorked += _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 20 hours, then finish. You can only work for the faction for 20 hours
if (this.timeWorked >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours) {
var maxCycles = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].GameCyclesPer20Hours;
this.timeWorked = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MillisecondsPer20Hours;
this.workHackExpGained = this.workHackExpGainRate * maxCycles;
this.workStrExpGained = this.workStrExpGainRate * maxCycles;
this.workDefExpGained = this.workDefExpGainRate * maxCycles;
this.workDexExpGained = this.workDexExpGainRate * maxCycles;
this.workAgiExpGained = this.workAgiExpGainRate * maxCycles;
this.workChaExpGained = this.workChaExpGainRate * maxCycles;
this.workRepGained = this.workRepGainRate * maxCycles;
this.workMoneyGained = this.workMoneyGainRate * maxCycles;
this.finishFactionWork(false);
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently " + this.currentWorkFactionDescription + " for your faction " + faction.name +
" (Current Faction Reputation: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(faction.playerReputation, 0) + "). " +
"You have been doing this for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"You have earned:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec)
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this faction
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp
" +
"You will automatically finish after working for 20 hours. You can cancel earlier if you wish.
" +
"There is no penalty for cancelling earlier.";
}
//Money gained per game cycle
PlayerObject.prototype.getWorkMoneyGain = function() {
var bn11Mult = 1;
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
if (_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_11__["hasBn11SF"]) {
bn11Mult = 1 + (company.favor / 100);
}
return this.companyPosition.baseSalary * company.salaryMultiplier *
this.work_money_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkMoney * bn11Mult;
}
//Hack exp gained per game cycle
PlayerObject.prototype.getWorkHackExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.hackingExpGain * company.expMultiplier *
this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Str exp gained per game cycle
PlayerObject.prototype.getWorkStrExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.strengthExpGain * company.expMultiplier *
this.strength_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Def exp gained per game cycle
PlayerObject.prototype.getWorkDefExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.defenseExpGain * company.expMultiplier *
this.defense_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Dex exp gained per game cycle
PlayerObject.prototype.getWorkDexExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.dexterityExpGain * company.expMultiplier *
this.dexterity_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Agi exp gained per game cycle
PlayerObject.prototype.getWorkAgiExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.agilityExpGain * company.expMultiplier *
this.agility_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Charisma exp gained per game cycle
PlayerObject.prototype.getWorkChaExpGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
return this.companyPosition.charismaExpGain * company.expMultiplier *
this.charisma_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CompanyWorkExpGain;
}
//Reputation gained per game cycle
PlayerObject.prototype.getWorkRepGain = function() {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
var jobPerformance = this.companyPosition.calculateJobPerformance(this.hacking_skill, this.strength,
this.defense, this.dexterity,
this.agility, this.charisma);
//Intelligence provides a flat bonus to job performance
jobPerformance += (this.intelligence / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel);
//Update reputation gain rate to account for company favor
var favorMult = 1 + (company.favor / 100);
if (isNaN(favorMult)) {favorMult = 1;}
return jobPerformance * this.company_rep_mult * favorMult;
}
PlayerObject.prototype.getFactionSecurityWorkRepGain = function() {
var t = 0.9 * (this.hacking_skill / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.strength / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.defense / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.dexterity / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.agility / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel) / 4.5;
return t * this.faction_rep_mult;
}
PlayerObject.prototype.getFactionFieldWorkRepGain = function() {
var t = 0.9 * (this.hacking_skill / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.strength / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.defense / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.dexterity / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.agility / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.charisma / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel +
this.intelligence / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].MaxSkillLevel) / 5.5;
return t * this.faction_rep_mult;
}
/* Creating a Program */
PlayerObject.prototype.startCreateProgramWork = function(programName, time, reqLevel) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCreateProgram;
//Time needed to complete work affected by hacking skill (linearly based on
//ratio of (your skill - required level) to MAX skill)
//var timeMultiplier = (CONSTANTS.MaxSkillLevel - (this.hacking_skill - reqLevel)) / CONSTANTS.MaxSkillLevel;
//if (timeMultiplier > 1) {timeMultiplier = 1;}
//if (timeMultiplier < 0.01) {timeMultiplier = 0.01;}
this.createProgramReqLvl = reqLevel;
this.timeNeededToCompleteWork = time;
//Check for incomplete program
for (var i = 0; i < this.getHomeComputer().programs.length; ++i) {
var programFile = this.getHomeComputer().programs[i];
if (programFile.startsWith(programName) && programFile.endsWith("%-INC")) {
var res = programFile.split("-");
if (res.length != 3) {break;}
var percComplete = Number(res[1].slice(0, -1));
if (isNaN(percComplete) || percComplete < 0 || percComplete >= 100) {break;}
this.timeWorkedCreateProgram = percComplete / 100 * this.timeNeededToCompleteWork;
this.getHomeComputer().programs.splice(i, 1);
}
}
this.createProgramName = programName;
var cancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button");
cancelButton.innerHTML = "Cancel work on creating program";
cancelButton.addEventListener("click", function() {
Player.finishCreateProgramWork(true);
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.createProgramWork = function(numCycles) {
//Higher hacking skill will allow you to create programs faster
var reqLvl = this.createProgramReqLvl;
var skillMult = (this.hacking_skill / reqLvl); //This should always be greater than 1;
skillMult = 1 + ((skillMult - 1) / 5); //The divider constant can be adjusted as necessary
//Skill multiplier directly applied to "time worked"
this.timeWorked += (_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles);
this.timeWorkedCreateProgram += (_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles * skillMult);
var programName = this.createProgramName;
if (this.timeWorkedCreateProgram >= this.timeNeededToCompleteWork) {
this.finishCreateProgramWork(false);
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working on coding " + programName + ".
" +
"You have been working for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"The program is " + (this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 100).toFixed(2) + "% complete.
" +
"If you cancel, your work will be saved and you can come back to complete the program later.";
}
PlayerObject.prototype.finishCreateProgramWork = function(cancelled, sing=false) {
var programName = this.createProgramName;
if (cancelled === false) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You've finished creating " + programName + "!
" +
"The new program can be found on your home computer.");
this.getHomeComputer().programs.push(programName);
} else {
var perc = (Math.floor(this.timeWorkedCreateProgram / this.timeNeededToCompleteWork * 10000)/100).toString();
var incompleteName = programName + "-" + perc + "%-INC";
this.getHomeComputer().programs.push(incompleteName);
}
if (!cancelled) {
this.gainIntelligenceExp(this.createProgramReqLvl / _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceProgramBaseExpGain);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadTerminalContent();
this.resetWorkStatus();
}
/* Studying/Taking Classes */
PlayerObject.prototype.startClass = function(costMult, expMult, className) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeStudyClass;
this.className = className;
var gameCPS = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed;
//Base exp gains per second
var baseStudyComputerScienceExp = 0.5;
var baseDataStructuresExp = 1;
var baseNetworksExp = 2;
var baseAlgorithmsExp = 4;
var baseManagementExp = 2;
var baseLeadershipExp = 4;
var baseGymExp = 1;
//Find cost and exp gain per game cycle
var cost = 0;
var hackExp = 0, strExp = 0, defExp = 0, dexExp = 0, agiExp = 0, chaExp = 0;
switch (className) {
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassStudyComputerScience:
hackExp = baseStudyComputerScienceExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassDataStructures:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassDataStructuresBaseCost * costMult / gameCPS;
hackExp = baseDataStructuresExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassNetworks:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassNetworksBaseCost * costMult / gameCPS;
hackExp = baseNetworksExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassAlgorithms:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassAlgorithmsBaseCost * costMult / gameCPS;
hackExp = baseAlgorithmsExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassManagement:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassManagementBaseCost * costMult / gameCPS;
chaExp = baseManagementExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassLeadership:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassLeadershipBaseCost * costMult / gameCPS;
chaExp = baseLeadershipExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymStrength:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
strExp = baseGymExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDefense:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
defExp = baseGymExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDexterity:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
dexExp = baseGymExp * expMult / gameCPS;
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymAgility:
cost = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymBaseCost * costMult / gameCPS;
agiExp = baseGymExp * expMult / gameCPS;
break;
default:
throw new Error("ERR: Invalid/unrecognized class name");
return;
}
this.workMoneyLossRate = cost;
this.workHackExpGainRate = hackExp * this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;
this.workStrExpGainRate = strExp * this.strength_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workDefExpGainRate = defExp * this.defense_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workDexExpGainRate = dexExp * this.dexterity_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workAgiExpGainRate = agiExp * this.agility_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
this.workChaExpGainRate = chaExp * this.charisma_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].ClassGymExpGain;;
var cancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button");
if (className == _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymStrength ||
className == _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDefense ||
className == _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymDexterity ||
className == _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].ClassGymAgility) {
cancelButton.innerHTML = "Stop training at gym";
} else {
cancelButton.innerHTML = "Stop taking course";
}
cancelButton.addEventListener("click", function() {
Player.finishClass();
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.takeClass = function(numCycles) {
this.timeWorked += _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles;
var className = this.className;
this.workHackExpGained += this.workHackExpGainRate * numCycles;
this.workStrExpGained += this.workStrExpGainRate * numCycles;
this.workDefExpGained += this.workDefExpGainRate * numCycles;
this.workDexExpGained += this.workDexExpGainRate * numCycles;
this.workAgiExpGained += this.workAgiExpGainRate * numCycles;
this.workChaExpGained += this.workChaExpGainRate * numCycles;
this.workRepGained += this.workRepGainRate * numCycles;
this.workMoneyGained += this.workMoneyGainRate * numCycles;
this.workMoneyGained -= this.workMoneyLossRate * numCycles;
var cyclesPerSec = 1000 / _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed;
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You have been " + className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + "
" +
"This has cost you:
" +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + " ($" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyLossRate * cyclesPerSec, 2) + " / sec)
" +
"You have gained:
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp
" +
"You may cancel at any time";
}
//The 'sing' argument defines whether or not this function was called
//through a Singularity Netscript function
PlayerObject.prototype.finishClass = function(sing=false) {
this.gainWorkExp();
this.gainIntelligenceExp(_Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].IntelligenceClassBaseExpGain * Math.round(this.timeWorked / 1000));
if (this.workMoneyGained > 0) {
throw new Error("ERR: Somehow gained money while taking class");
}
this.loseMoney(this.workMoneyGained * -1);
this.updateSkillLevels();
var txt = "After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ",
" +
"you spent a total of $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained * -1, 2) + ".
" +
"You earned a total of:
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility exp
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma exp
";
if (!sing) {Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
if (sing) {
var res="After " + this.className + " for " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeWorked) + ", " +
"you spent a total of $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained * -1, 2) + ". " +
"You earned a total of: " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 3) + " hacking exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 3) + " strength exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 3) + " defense exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 3) + " dexterity exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 3) + " agility exp, and " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 3) + " charisma exp";
this.resetWorkStatus();
return res;
}
this.resetWorkStatus();
}
//The EXP and $ gains are hardcoded. Time is in ms
PlayerObject.prototype.startCrime = function(hackExp, strExp, defExp, dexExp, agiExp, chaExp, money, time, singParams=null) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCrime;
if (singParams && singParams.workerscript) {
this.committingCrimeThruSingFn = true;
this.singFnCrimeWorkerScript = singParams.workerscript;
}
this.workHackExpGained = hackExp * this.hacking_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workStrExpGained = strExp * this.strength_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workDefExpGained = defExp * this.defense_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workDexExpGained = dexExp * this.dexterity_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workAgiExpGained = agiExp * this.agility_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workChaExpGained = chaExp * this.charisma_exp_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeExpGain;
this.workMoneyGained = money * this.crime_money_mult * _BitNode_js__WEBPACK_IMPORTED_MODULE_1__["BitNodeMultipliers"].CrimeMoney;
this.timeNeededToCompleteWork = time;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_17__["clearEventListeners"])("work-in-progress-cancel-button")
newCancelButton.innerHTML = "Cancel crime"
newCancelButton.addEventListener("click", function() {
Player.finishCrime(true);
return false;
});
//Display Work In Progress Screen
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.commitCrime = function (numCycles) {
this.timeWorked += _engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"]._idleSpeed * numCycles;
if (this.timeWorked >= this.timeNeededToCompleteWork) {this.finishCrime(false); return;}
var percent = Math.round(this.timeWorked / this.timeNeededToCompleteWork * 100);
var numBars = Math.round(percent / 5);
if (numBars < 0) {numBars = 0;}
if (numBars > 20) {numBars = 20;}
var progressBar = "[" + Array(numBars+1).join("|") + Array(20 - numBars + 1).join(" ") + "]";
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are attempting to " + this.crimeType + ".
" +
"Time remaining: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["convertTimeMsToTimeElapsedString"])(this.timeNeededToCompleteWork - this.timeWorked) + "
" +
progressBar.replace( / /g, " " );
}
PlayerObject.prototype.finishCrime = function(cancelled) {
//Determine crime success/failure
if (!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
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;
}
}
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
this.workHackExpGained *= 2;
this.workStrExpGained *= 2;
this.workDefExpGained *= 2;
this.workDexExpGained *= 2;
this.workAgiExpGained *= 2;
this.workChaExpGained *= 2;
if (this.committingCrimeThruSingFn) {
if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) {
this.singFnCrimeWorkerScript.scriptRef.log("Crime successful! Gained " +
numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_20___default()(this.workMoneyGained).format("$0.000a") + ", " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 3) + " hack exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 3) + " str exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 3) + " def exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 3) + " dex exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 3) + " agi exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 3) + " cha exp.");
}
} else {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Crime successful!
" +
"You gained:
"+
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workMoneyGained, 2) + "
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma experience");
}
} else {
//Exp halved on failure
this.workHackExpGained /= 2;
this.workStrExpGained /= 2;
this.workDefExpGained /= 2;
this.workDexExpGained /= 2;
this.workAgiExpGained /= 2;
this.workChaExpGained /= 2;
if (this.committingCrimeThruSingFn) {
if(this.singFnCrimeWorkerScript.disableLogs.ALL == null && this.singFnCrimeWorkerScript.disableLogs.commitCrime == null) {
this.singFnCrimeWorkerScript.scriptRef.log("Crime failed! Gained " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 3) + " hack exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 3) + " str exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 3) + " def exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 3) + " dex exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 3) + " agi exp, " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 3) + " cha exp.");
}
} else {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Crime failed!
" +
"You gained:
"+
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workHackExpGained, 4) + " hacking experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workStrExpGained, 4) + " strength experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDefExpGained, 4) + " defense experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workDexExpGained, 4) + " dexterity experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workAgiExpGained, 4) + " agility experience
" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.workChaExpGained, 4) + " charisma experience");
}
}
this.gainWorkExp();
}
this.committingCrimeThruSingFn = false;
this.singFnCrimeWorkerScript = null;
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
this.resetWorkStatus();
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
}
//Cancels the player's current "work" assignment and gives the proper rewards
//Used only for Singularity functions, so no popups are created
PlayerObject.prototype.singularityStopWork = function() {
if (!this.isWorking) {return "";}
var res; //Earnings text for work
switch (this.workType) {
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeStudyClass:
res = this.finishClass(true);
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompany:
res = this.finishWork(true, true);
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCompanyPartTime:
res = this.finishWorkPartTime(true);
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeFaction:
res = this.finishFactionWork(true, true);
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCreateProgram:
res = this.finishCreateProgramWork(true, true);
break;
case _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].WorkTypeCrime:
res = this.finishCrime(true);
break;
default:
console.log("ERROR: Unrecognized work type");
return "";
}
return res;
}
//Returns true if hospitalized, false otherwise
PlayerObject.prototype.takeDamage = function(amt) {
this.hp -= amt;
if (this.hp <= 0) {
this.hospitalize();
return true;
} else {
return false;
}
}
PlayerObject.prototype.hospitalize = function() {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You were in critical condition! You were taken to the hospital where " +
"luckily they were able to save your life. You were charged $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_21__["formatNumber"])(this.max_hp * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp, 2));
this.loseMoney(this.max_hp * _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].HospitalCostPerHp);
this.hp = this.max_hp;
}
/********* Company job application **********/
//Determines the job that the Player should get (if any) at the current company
//The 'sing' argument designates whether or not this is being called from
//the applyToCompany() Netscript Singularity function
PlayerObject.prototype.applyForJob = function(entryPosType, sing=false) {
var currCompany = "";
if (this.companyName != "") {
currCompany = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
}
var currPositionName = "";
if (this.companyPosition != "") {
currPositionName = this.companyPosition.positionName;
}
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (sing && !(company instanceof _Company_js__WEBPACK_IMPORTED_MODULE_2__["Company"])) {
return "ERROR: Invalid company name: " + this.location + ". applyToCompany() failed";
}
var pos = entryPosType;
if (!this.isQualified(company, pos)) {
var reqText = Object(_Company_js__WEBPACK_IMPORTED_MODULE_2__["getJobRequirementText"])(company, pos);
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position
" + reqText);
return;
}
while (true) {
if (_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].Debug) {console.log("Determining qualification for next Company Position");}
var newPos = Object(_Company_js__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(pos);
if (newPos == null) {break;}
//Check if this company has this position
if (company.hasPosition(newPos)) {
if (!this.isQualified(company, newPos)) {
//If player not qualified for next job, break loop so player will be given current job
break;
}
pos = newPos;
} else {
break;
}
}
//Check if the determined job is the same as the player's current job
if (currCompany != "") {
if (currCompany.companyName == company.companyName &&
pos.positionName == currPositionName) {
var nextPos = Object(_Company_js__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(pos);
if (nextPos == null) {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available");
} else if (company.hasPosition(nextPos)) {
if (sing) {return false;}
var reqText = Object(_Company_js__WEBPACK_IMPORTED_MODULE_2__["getJobRequirementText"])(company, nextPos);
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unfortunately, you do not qualify for a promotion
" + reqText);
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("You are already at the highest position for your field! No promotion available");
}
return; //Same job, do nothing
}
}
//Lose reputation from a Company if you are leaving it for another job
var leaveCompany = false;
var oldCompanyName = "";
if (currCompany != "") {
if (currCompany.companyName != company.companyName) {
leaveCompany = true;
oldCompanyName = currCompany.companyName;
company.playerReputation -= 1000;
if (company.playerReputation < 0) {company.playerReputation = 0;}
}
}
this.companyName = company.companyName;
this.companyPosition = pos;
if (this.firstJobRecvd === false) {
this.firstJobRecvd = true;
document.getElementById("job-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
if (leaveCompany) {
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " +
pos.positionName + "!
" +
"You lost 1000 reputation at your old company " + oldCompanyName + " because you left.");
} else {
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.positionName + "!");
}
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
}
//Returns your next position at a company given the field (software, business, etc.)
PlayerObject.prototype.getNextCompanyPosition = function(company, entryPosType) {
var currCompany = null;
if (this.companyName != "") {
currCompany = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
}
//Not employed at this company, so return the entry position
if (currCompany == null || (currCompany.companyName != company.companyName)) {
return entryPosType;
}
//If the entry pos type and the player's current position have the same type,
//return the player's "nextCompanyPosition". Otherwise return the entryposType
//Employed at this company, so just return the next position if it exists.
if ((this.companyPosition.isSoftwareJob() && entryPosType.isSoftwareJob()) ||
(this.companyPosition.isITJob() && entryPosType.isITJob()) ||
(this.companyPosition.isBusinessJob() && entryPosType.isBusinessJob()) ||
(this.companyPosition.isSecurityEngineerJob() && entryPosType.isSecurityEngineerJob()) ||
(this.companyPosition.isNetworkEngineerJob() && entryPosType.isNetworkEngineerJob()) ||
(this.companyPosition.isSecurityJob() && entryPosType.isSecurityJob()) ||
(this.companyPosition.isAgentJob() && entryPosType.isAgentJob()) ||
(this.companyPosition.isSoftwareConsultantJob() && entryPosType.isSoftwareConsultantJob()) ||
(this.companyPosition.isBusinessConsultantJob() && entryPosType.isBusinessConsultantJob()) ||
(this.companyPosition.isPartTimeJob() && entryPosType.isPartTimeJob())) {
return Object(_Company_js__WEBPACK_IMPORTED_MODULE_2__["getNextCompanyPosition"])(this.companyPosition);
}
return entryPosType;
}
PlayerObject.prototype.applyForSoftwareJob = function(sing=false) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SoftwareIntern, sing);
}
PlayerObject.prototype.applyForSoftwareConsultantJob = function(sing=false) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SoftwareConsultant, sing);
}
PlayerObject.prototype.applyForItJob = function(sing=false) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].ITIntern, sing);
}
PlayerObject.prototype.applyForSecurityEngineerJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityEngineer)) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityEngineer, sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForNetworkEngineerJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].NetworkEngineer)) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].NetworkEngineer, sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForBusinessJob = function(sing=false) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].BusinessIntern, sing);
}
PlayerObject.prototype.applyForBusinessConsultantJob = function(sing=false) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].BusinessConsultant, sing);
}
PlayerObject.prototype.applyForSecurityJob = function(sing=false) {
//TODO If case for POlice departments
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].SecurityGuard, sing);
}
PlayerObject.prototype.applyForAgentJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].FieldAgent)) {
return this.applyForJob(_Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].FieldAgent, sing);
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForEmployeeJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Employee)) {
if (this.firstJobRecvd === false) {
this.firstJobRecvd = true;
document.getElementById("job-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
this.companyName = company.companyName;
this.companyPosition = _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Employee;
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed at " + this.companyName);
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeEmployeeJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeEmployee)) {
if (this.firstJobRecvd === false) {
this.firstJobRecvd = true;
document.getElementById("job-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
this.companyName = company.companyName;
this.companyPosition = _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeEmployee;
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed part-time at " + this.companyName);
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForWaiterJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Waiter)) {
if (this.firstJobRecvd === false) {
this.firstJobRecvd = true;
document.getElementById("job-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
this.companyName = company.companyName;
this.companyPosition = _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].Waiter;
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed as a waiter at " + this.companyName);
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeWaiterJob = function(sing=false) {
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.location]; //Company being applied to
if (this.isQualified(company, _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeWaiter)) {
if (this.firstJobRecvd === false) {
this.firstJobRecvd = true;
document.getElementById("job-tab").style.display = "list-item";
document.getElementById("world-menu-header").click();
document.getElementById("world-menu-header").click();
}
this.companyName = company.companyName;
this.companyPosition = _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].PartTimeWaiter;
if (sing) {return true;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Congratulations, you are now employed as a part-time waiter at " + this.companyName);
_engine_js__WEBPACK_IMPORTED_MODULE_7__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_16__["dialogBoxCreate"])("Unforunately, you do not qualify for this position");
}
}
//Checks if the Player is qualified for a certain position
PlayerObject.prototype.isQualified = function(company, position) {
var offset = company.jobStatReqOffset;
var reqHacking = position.requiredHacking > 0 ? position.requiredHacking+offset : 0;
var reqStrength = position.requiredStrength > 0 ? position.requiredStrength+offset : 0;
var reqDefense = position.requiredDefense > 0 ? position.requiredDefense+offset : 0;
var reqDexterity = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0;
var reqAgility = position.requiredDexterity > 0 ? position.requiredDexterity+offset : 0;
var reqCharisma = position.requiredCharisma > 0 ? position.requiredCharisma+offset : 0;
if (this.hacking_skill >= reqHacking &&
this.strength >= reqStrength &&
this.defense >= reqDefense &&
this.dexterity >= reqDexterity &&
this.agility >= reqAgility &&
this.charisma >= reqCharisma &&
company.playerReputation >= position.requiredReputation) {
return true;
}
return false;
}
/********** Reapplying Augmentations and Source File ***********/
PlayerObject.prototype.reapplyAllAugmentations = function(resetMultipliers=true) {
console.log("Re-applying augmentations");
if (resetMultipliers) {
this.resetMultipliers();
}
for (let i = 0; i < this.augmentations.length; ++i) {
//Compatibility with new version
if (this.augmentations[i].name === "HacknetNode NIC Architecture Neural-Upload") {
this.augmentations[i].name = "Hacknet Node NIC Architecture Neural-Upload";
}
var augName = this.augmentations[i].name;
var aug = _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][augName];
if (aug == null) {
console.log("WARNING: Invalid augmentation name");
continue;
}
aug.owned = true;
if (aug.name == _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].NeuroFluxGovernor) {
for (let j = 0; j < aug.level; ++j) {
Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["applyAugmentation"])(this.augmentations[i], true);
}
continue;
}
Object(_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["applyAugmentation"])(this.augmentations[i], true);
}
}
PlayerObject.prototype.reapplyAllSourceFiles = function() {
console.log("Re-applying source files");
//Will always be called after reapplyAllAugmentations() so multipliers do not have to be reset
//this.resetMultipliers();
for (let i = 0; i < this.sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + this.sourceFiles[i].n;
var sourceFileObject = _SourceFile_js__WEBPACK_IMPORTED_MODULE_14__["SourceFiles"][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + this.sourceFiles[i].n);
continue;
}
Object(_SourceFile_js__WEBPACK_IMPORTED_MODULE_14__["applySourceFile"])(this.sourceFiles[i]);
}
}
/*************** Check for Faction Invitations *************/
//This function sets the requirements to join a Faction. It checks whether the Player meets
//those requirements and will return an array of all factions that the Player should
//receive an invitation to
PlayerObject.prototype.checkForFactionInvitations = function() {
let invitedFactions = []; //Array which will hold all Factions th eplayer should be invited to
var numAugmentations = this.augmentations.length;
var company = _Company_js__WEBPACK_IMPORTED_MODULE_2__["Companies"][this.companyName];
var companyRep = 0;
if (company != null) {
companyRep = company.playerReputation;
}
//Illuminati
var illuminatiFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Illuminati"];
if (!illuminatiFac.isBanned && !illuminatiFac.isMember && !illuminatiFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(150000000000) &&
this.hacking_skill >= 1500 &&
this.strength >= 1200 && this.defense >= 1200 &&
this.dexterity >= 1200 && this.agility >= 1200) {
invitedFactions.push(illuminatiFac);
}
//Daedalus
var daedalusFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Daedalus"];
if (!daedalusFac.isBanned && !daedalusFac.isMember && !daedalusFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(100000000000) &&
(this.hacking_skill >= 2500 ||
(this.strength >= 1500 && this.defense >= 1500 &&
this.dexterity >= 1500 && this.agility >= 1500))) {
invitedFactions.push(daedalusFac);
}
//The Covenant
var covenantFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Covenant"];
if (!covenantFac.isBanned && !covenantFac.isMember && !covenantFac.alreadyInvited &&
numAugmentations >= 30 &&
this.money.gte(75000000000) &&
this.hacking_skill >= 850 &&
this.strength >= 850 &&
this.defense >= 850 &&
this.dexterity >= 850 &&
this.agility >= 850) {
invitedFactions.push(covenantFac);
}
//ECorp
var ecorpFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["ECorp"];
if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumECorp && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(ecorpFac);
}
//MegaCorp
var megacorpFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["MegaCorp"];
if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12MegaCorp && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(megacorpFac);
}
//Bachman & Associates
var bachmanandassociatesFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Bachman & Associates"];
if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember &&
!bachmanandassociatesFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumBachmanAndAssociates && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(bachmanandassociatesFac);
}
//Blade Industries
var bladeindustriesFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Blade Industries"];
if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12BladeIndustries && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(bladeindustriesFac);
}
//NWO
var nwoFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["NWO"];
if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].VolhavenNWO && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(nwoFac);
}
//Clarke Incorporated
var clarkeincorporatedFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Clarke Incorporated"];
if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumClarkeIncorporated && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(clarkeincorporatedFac);
}
//OmniTek Incorporated
var omnitekincorporatedFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["OmniTek Incorporated"];
if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].VolhavenOmniTekIncorporated && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(omnitekincorporatedFac);
}
//Four Sigma
var foursigmaFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Four Sigma"];
if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12FourSigma && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(foursigmaFac);
}
//KuaiGong International
var kuaigonginternationalFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["KuaiGong International"];
if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember &&
!kuaigonginternationalFac.alreadyInvited &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].ChongqingKuaiGongInternational && companyRep >= _Constants_js__WEBPACK_IMPORTED_MODULE_3__["CONSTANTS"].CorpFactionRepRequirement) {
invitedFactions.push(kuaigonginternationalFac);
}
//Fulcrum Secret Technologies - If u've unlocked fulcrum secret technolgoies server and have a high rep with the company
var fulcrumsecrettechonologiesFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Fulcrum Secret Technologies"];
var fulcrumSecretServer = _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].FulcrumSecretTechnologies]];
if (fulcrumSecretServer == null) {
console.log("ERROR: Could not find Fulcrum Secret Technologies Server");
} else {
if (!fulcrumsecrettechonologiesFac.isBanned && !fulcrumsecrettechonologiesFac.isMember &&
!fulcrumsecrettechonologiesFac.alreadyInvited &&
fulcrumSecretServer.manuallyHacked &&
this.companyName == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].AevumFulcrumTechnologies && companyRep >= 250000) {
invitedFactions.push(fulcrumsecrettechonologiesFac);
}
}
//BitRunners
var bitrunnersFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["BitRunners"];
var homeComp = this.getHomeComputer();
var bitrunnersServer = _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].BitRunnersServer]];
if (bitrunnersServer == null) {
console.log("ERROR: Could not find BitRunners Server");
} else if (!bitrunnersFac.isBanned && !bitrunnersFac.isMember && bitrunnersServer.manuallyHacked &&
!bitrunnersFac.alreadyInvited && this.hacking_skill >= 500 && homeComp.maxRam >= 128) {
invitedFactions.push(bitrunnersFac);
}
//The Black Hand
var theblackhandFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Black Hand"];
var blackhandServer = _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].TheBlackHandServer]];
if (blackhandServer == null) {
console.log("ERROR: Could not find The Black Hand Server");
} else if (!theblackhandFac.isBanned && !theblackhandFac.isMember && blackhandServer.manuallyHacked &&
!theblackhandFac.alreadyInvited && this.hacking_skill >= 350 && homeComp.maxRam >= 64) {
invitedFactions.push(theblackhandFac);
}
//NiteSec
var nitesecFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["NiteSec"];
var nitesecServer = _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].NiteSecServer]];
if (nitesecServer == null) {
console.log("ERROR: Could not find NiteSec Server");
} else if (!nitesecFac.isBanned && !nitesecFac.isMember && nitesecServer.manuallyHacked &&
!nitesecFac.alreadyInvited && this.hacking_skill >= 200 && homeComp.maxRam >= 32) {
invitedFactions.push(nitesecFac);
}
//Chongqing
var chongqingFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Chongqing"];
if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited &&
this.money.gte(20000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing) {
invitedFactions.push(chongqingFac);
}
//Sector-12
var sector12Fac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Sector-12"];
if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited &&
this.money.gte(15000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12) {
invitedFactions.push(sector12Fac);
}
//New Tokyo
var newtokyoFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["New Tokyo"];
if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited &&
this.money.gte(20000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo) {
invitedFactions.push(newtokyoFac);
}
//Aevum
var aevumFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Aevum"];
if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited &&
this.money.gte(40000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Aevum) {
invitedFactions.push(aevumFac);
}
//Ishima
var ishimaFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Ishima"];
if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited &&
this.money.gte(30000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima) {
invitedFactions.push(ishimaFac);
}
//Volhaven
var volhavenFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Volhaven"];
if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited &&
this.money.gte(50000000) && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Volhaven) {
invitedFactions.push(volhavenFac);
}
//Speakers for the Dead
var speakersforthedeadFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Speakers for the Dead"];
if (!speakersforthedeadFac.isBanned && !speakersforthedeadFac.isMember && !speakersforthedeadFac.alreadyInvited &&
this.hacking_skill >= 100 && this.strength >= 300 && this.defense >= 300 &&
this.dexterity >= 300 && this.agility >= 300 && this.numPeopleKilled >= 30 &&
this.karma <= -45 && this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA &&
this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) {
invitedFactions.push(speakersforthedeadFac);
}
//The Dark Army
var thedarkarmyFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Dark Army"];
if (!thedarkarmyFac.isBanned && !thedarkarmyFac.isMember && !thedarkarmyFac.alreadyInvited &&
this.hacking_skill >= 300 && this.strength >= 300 && this.defense >= 300 &&
this.dexterity >= 300 && this.agility >= 300 && this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing &&
this.numPeopleKilled >= 5 && this.karma <= -45 && this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA &&
this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) {
invitedFactions.push(thedarkarmyFac);
}
//The Syndicate
var thesyndicateFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["The Syndicate"];
if (!thesyndicateFac.isBanned && !thesyndicateFac.isMember && !thesyndicateFac.alreadyInvited &&
this.hacking_skill >= 200 && this.strength >= 200 && this.defense >= 200 &&
this.dexterity >= 200 && this.agility >= 200 &&
(this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Aevum || this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12) &&
this.money.gte(10000000) && this.karma <= -90 &&
this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12CIA && this.companyName != _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Sector12NSA) {
invitedFactions.push(thesyndicateFac);
}
//Silhouette
var silhouetteFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Silhouette"];
if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited &&
(this.companyPosition.positionName == _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CTO.positionName ||
this.companyPosition.positionName == _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CFO.positionName ||
this.companyPosition.positionName == _Company_js__WEBPACK_IMPORTED_MODULE_2__["CompanyPositions"].CEO.positionName) &&
this.money.gte(15000000) && this.karma <= -22) {
invitedFactions.push(silhouetteFac);
}
//Tetrads
var tetradsFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Tetrads"];
if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited &&
(this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing || this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo ||
this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima) && this.strength >= 75 && this.defense >= 75 &&
this.dexterity >= 75 && this.agility >= 75 && this.karma <= -18) {
invitedFactions.push(tetradsFac);
}
//SlumSnakes
var slumsnakesFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Slum Snakes"];
if (!slumsnakesFac.isBanned && !slumsnakesFac.isMember && !slumsnakesFac.alreadyInvited &&
this.strength >= 30 && this.defense >= 30 && this.dexterity >= 30 &&
this.agility >= 30 && this.karma <= -9 && this.money.gte(1000000)) {
invitedFactions.push(slumsnakesFac);
}
//Netburners
var netburnersFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Netburners"];
var totalHacknetRam = 0;
var totalHacknetCores = 0;
var totalHacknetLevels = 0;
for (var i = 0; i < this.hacknetNodes.length; ++i) {
totalHacknetLevels += this.hacknetNodes[i].level;
totalHacknetRam += this.hacknetNodes[i].ram;
totalHacknetCores += this.hacknetNodes[i].cores;
}
if (!netburnersFac.isBanned && !netburnersFac.isMember && !netburnersFac.alreadyInvited &&
this.hacking_skill >= 80 && totalHacknetRam >= 8 &&
totalHacknetCores >= 4 && totalHacknetLevels >= 100) {
invitedFactions.push(netburnersFac);
}
//Tian Di Hui
var tiandihuiFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["Tian Di Hui"];
if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited &&
this.money.gte(1000000) && this.hacking_skill >= 50 &&
(this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Chongqing || this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].NewTokyo ||
this.city == _Location_js__WEBPACK_IMPORTED_MODULE_10__["Locations"].Ishima)) {
invitedFactions.push(tiandihuiFac);
}
//CyberSec
var cybersecFac = _Faction_js__WEBPACK_IMPORTED_MODULE_8__["Factions"]["CyberSec"];
var cybersecServer = _Server_js__WEBPACK_IMPORTED_MODULE_12__["AllServers"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerIps"][_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_13__["SpecialServerNames"].CyberSecServer]];
if (cybersecServer == null) {
console.log("ERROR: Could not find CyberSec Server");
} else if (!cybersecFac.isBanned && !cybersecFac.isMember && cybersecServer.manuallyHacked &&
!cybersecFac.alreadyInvited && this.hacking_skill >= 50) {
invitedFactions.push(cybersecFac);
}
return invitedFactions;
}
/*************** Gang ****************/
//Returns true if Player is in a gang and false otherwise
PlayerObject.prototype.inGang = function() {
if (this.gang == null || this.gang == undefined) {return false;}
return (this.gang instanceof _Gang_js__WEBPACK_IMPORTED_MODULE_9__["Gang"]);
}
PlayerObject.prototype.startGang = function(factionName, hacking) {
this.gang = new _Gang_js__WEBPACK_IMPORTED_MODULE_9__["Gang"](factionName, hacking);
}
/************* BitNodes **************/
PlayerObject.prototype.setBitNodeNumber = function(n) {
this.bitNodeN = n;
}
PlayerObject.prototype.queueAugmentation = function(name) {
for(const i in this.queuedAugmentations) {
if(this.queuedAugmentations[i].name == name) {
console.log('tried to queue '+name+' twice, this may be a bug');
return;
}
}
for(const i in this.augmentations) {
if(this.augmentations[i].name == name) {
console.log('tried to queue '+name+' but we already have that aug');
return;
}
}
this.firstAugPurchased = true;
this.queuedAugmentations.push(new _Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["PlayerOwnedAugmentation"](name));
}
/* Functions for saving and loading the Player data */
function loadPlayer(saveString) {
Player = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__["Reviver"]);
//Parse Decimal.js objects
Player.money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.money);
Player.total_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.total_money);
Player.lifetime_money = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.lifetime_money);
if (Player.corporation instanceof _CompanyManagement_js__WEBPACK_IMPORTED_MODULE_4__["Corporation"]) {
Player.corporation.funds = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.funds);
Player.corporation.revenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.revenue);
Player.corporation.expenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](Player.corporation.expenses);
for (var i = 0; i < Player.corporation.divisions.length; ++i) {
var ind = Player.corporation.divisions[i];
ind.lastCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.lastCycleRevenue);
ind.lastCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.lastCycleExpenses);
ind.thisCycleRevenue = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.thisCycleRevenue);
ind.thisCycleExpenses = new decimal_js__WEBPACK_IMPORTED_MODULE_15__["default"](ind.thisCycleExpenses);
}
}
}
PlayerObject.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__["Generic_toJSON"])("PlayerObject", this);
}
PlayerObject.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__["Generic_fromJSON"])(PlayerObject, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_19__["Reviver"].constructors.PlayerObject = PlayerObject;
let Player = new PlayerObject();
/***/ }),
/* 1 */
/*!**********************************!*\
!*** ./utils/HelperFunctions.js ***!
\**********************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sizeOfObject", function() { return sizeOfObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearObject", function() { return clearObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addOffset", function() { return addOffset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearEventListeners", function() { return clearEventListeners; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRandomInt", function() { return getRandomInt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "compareArrays", function() { return compareArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "printArray", function() { return printArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "powerOfTwo", function() { return powerOfTwo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearEventListenersEl", function() { return clearEventListenersEl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeElementById", function() { return removeElementById; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeElement", function() { return removeElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createElement", function() { return createElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAccordionElement", function() { return createAccordionElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendLineBreaks", function() { return appendLineBreaks; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeChildrenFromElement", function() { return removeChildrenFromElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPopup", function() { return createPopup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearSelector", function() { return clearSelector; });
/* 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 export (binding) */ __webpack_require__.d(__webpack_exports__, "getElementById", function() { return getElementById; });
/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StringHelperFunctions */ 2);
/* harmony import */ var _StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _DialogBox_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DialogBox.js */ 6);
//General helper functions
//Returns the size (number of keys) of an object
function sizeOfObject(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
}
function clearObject(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
delete obj[key];
}
}
}
//Adds a random offset to a number within a certain percentage
//e.g. addOffset(100, 5) will return anything from 95 to 105.
//The percentage argument must be between 0 and 100;
function addOffset(n, percentage) {
if (percentage < 0 || percentage > 100) {return n;}
var offset = n * (percentage / 100);
return n + ((Math.random() * (2 * offset)) - offset);
}
//Given an element by its Id(usually an 'a' element), removes all event listeners
//from that element by cloning and replacing. Then returns the new cloned element
function clearEventListeners(elemId) {
var elem = document.getElementById(elemId);
if (elem == null) {console.log("ERR: Could not find element for: " + elemId); return null;}
var newElem = elem.cloneNode(true);
elem.parentNode.replaceChild(newElem, elem);
return newElem;
}
//Same as clearEventListeners except it takes a DOM element object rather than an ID
function clearEventListenersEl(el) {
if (el == null) {console.log("ERR: element passed into clearEventListenersEl is null"); return null;}
var newElem = el.cloneNode(true);
el.parentNode.replaceChild(newElem, el);
return newElem;
}
//Given its id, this function removes an element AND its children
function removeElementById(id) {
var elem = document.getElementById(id);
if (elem == null) {return;}
while(elem.firstChild) {elem.removeChild(elem.firstChild);}
elem.parentNode.removeChild(elem);
}
function removeElement(elem) {
if (elem == null || !(elem instanceof Element)) {return;}
while(elem.firstChild) {elem.removeChild(elem.firstChild);}
elem.parentNode.removeChild(elem);
}
function removeChildrenFromElement(el) {
if (Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_0__["isString"])(el)) {
el = document.getElementById(el);
}
if (el == null) {return;}
if (el instanceof Element) {
while(el.firstChild) {
el.removeChild(el.firstChild);
}
}
}
/**
* Returns a reference to the first object with the specified value of the ID or NAME attribute, throwing an error if it is unable to find it.
* @param {string} elementId The HTML ID to retrieve the element by.
* @returns {HTMLElement} The single element.
* @throws {Error} When the 'idString' cannot be found.
*/
function getElementById(elementId) {
var el = document.getElementById(elementId);
if (el == null) {
throw new Error("Unable to find element with id '" + elementId + "'");
}
return el;
}
function createElement(type, params={}) {
var el = document.createElement(type);
if (params.id) {el.id = params.id;}
if (params.class) {el.className = params.class;}
if (params.name) {el.name = params.name;}
if (params.innerHTML) {el.innerHTML = params.innerHTML;}
if (params.innerText) {el.innerText = params.innerText;}
if (params.value) {el.value = params.value;}
if (params.text) {el.text = params.text;}
if (params.display) {el.style.display = params.display;}
if (params.visibility) {el.style.visibility = params.visibility;}
if (params.margin) {el.style.margin = params.margin;}
if (params.marginLeft) {el.style.marginLeft = params.marginLeft;}
if (params.marginTop) {el.style.marginTop = params.marginTop;}
if (params.padding) {el.style.padding = params.padding;}
if (params.color) {el.style.color = params.color;}
if (params.border) {el.style.border = params.border;}
if (params.float) {el.style.cssFloat = params.float;}
if (params.fontSize) {el.style.fontSize = params.fontSize;}
if (params.whiteSpace) {el.style.whiteSpace = params.whiteSpace;}
if (params.width) {el.style.width = params.width;}
if (params.backgroundColor) {
el.style.backgroundColor = params.backgroundColor
}
if (params.position) {el.style.position = params.position;}
if (params.type) {el.type = params.type;}
if (params.checked) {el.checked = params.checked;}
if (params.for) {el.htmlFor = params.for;}
if (params.pattern) {el.pattern = params.pattern;}
if (params.maxLength) {el.maxLength = params.maxLength;}
if (params.placeholder) {el.placeholder = params.placeholder;}
if (params.tooltip && params.tooltip !== "") {
el.className += " tooltip";
el.appendChild(createElement("span", {
class:"tooltiptext",
innerHTML:params.tooltip
}));
} else if (params.tooltipleft) {
el.className += " tooltip";
el.appendChild(createElement("span", {
class:"tooltiptextleft",
innerHTML:params.tooltipleft
}));
}
if (params.href) {el.href = params.href;}
if (params.target) {el.target = params.target;}
if (params.tabIndex) {el.tabIndex = params.tabIndex;}
if (params.clickListener) {
el.addEventListener("click", params.clickListener);
}
if (params.inputListener) {
el.addEventListener("input", params.inputListener);
}
if (params.changeListener) {
el.addEventListener("change", params.changeListener);
}
if (params.onkeyup) {
el.addEventListener("keyup", params.onkeyup);
}
if (params.onfocus) {
el.addEventListener("focus", params.onfocus);
}
return el;
}
function createPopup(id, elems) {
var container = createElement("div", {
class:"popup-box-container",
id:id,
display:"block"
}),
content = createElement("div", {
class:"popup-box-content",
id:id + "-content",
});
for (var i = 0; i < elems.length; ++i) {
content.appendChild(elems[i]);
}
container.appendChild(content);
document.getElementById("entire-game-container").appendChild(container);
return container;
}
//Creates both the header and panel element of an accordion and sets the click handler
function createAccordionElement(params) {
var li = document.createElement("li"),
hdr = document.createElement("button"),
panel = document.createElement("div");
hdr.classList.add("accordion-header");
panel.classList.add("accordion-panel");
if (params.id) {
hdr.id = params.id + "-hdr";
panel.id = params.id + "-panel";
}
if (params.hdrText) {hdr.innerHTML = params.hdrText;}
if (params.panelText) {panel.innerHTML = params.panelText;}
li.appendChild(hdr);
li.appendChild(panel);
//Click handler
hdr.onclick = function() {
this.classList.toggle("active");
var tmpPanel = this.nextElementSibling;
if (tmpPanel.style.display === "block") {
tmpPanel.style.display = "none";
} else {
tmpPanel.style.display = "block";
}
}
return [li, hdr, panel];
}
//Appends n line breaks (as children) to the Element el
function appendLineBreaks(el, n) {
for (var i = 0; i < n; ++i) {
el.appendChild(createElement("br"));
}
}
function clearSelector(selector) {
for (var i = selector.options.length - 1; i >= 0; --i) {
selector.remove(i);
}
}
function getRandomInt(min, max) {
if (min > max) {return getRandomInt(max, min);}
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//Returns true if all elements are equal, and false otherwise
//Assumes both arguments are arrays and that there are no nested arrays
function compareArrays(a1, a2) {
if (a1.length != a2.length) {
return false;
}
for (var i = 0; i < a1.length; ++i) {
if (a1[i] != a2[i]) {return false;}
}
return true;
}
function printArray(a) {
return "[" + a.join(", ") + "]";
}
//Returns bool indicating whether or not its a power of 2
function powerOfTwo(n) {
if (isNaN(n)) {return false;}
return n && (n & (n-1)) === 0;
}
function exceptionAlert(e) {
Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_1__["dialogBoxCreate"])("Caught an exception: " + e + "
" +
"Filename: " + e.fileName + "
" +
"Line Number: " + e.lineNumber + "
" +
"This is a bug, please report to game developer with this " +
"message as well as details about how to reproduce the bug.
" +
"If you want to be safe, I suggest refreshing the game WITHOUT saving so that your " +
"safe doesn't get corrupted");
}
/*Creates a graphical "progress bar"
* e.g.: [||||---------------]
* params:
* @totalTicks - Total number of ticks in progress bar. Preferably a factor of 100
* @progress - Current progress, taken as a decimal (i.e. 0.6 to represent 60%)
*/
function createProgressBarText(params={}) {
//Default values
var totalTicks = (params.totalTicks == null ? 20 : params.totalTicks);
var progress = (params.progress == null ? 0 : params.progress);
var percentPerTick = 1 / totalTicks;
var numTicks = Math.floor(progress / percentPerTick);
var numDashes = totalTicks - numTicks;
return "[" + Array(numTicks+1).join("|") + Array(numDashes+1).join("-") + "]";
}
/***/ }),
/* 2 */
/*!****************************************!*\
!*** ./utils/StringHelperFunctions.ts ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DialogBox_js_1 = __webpack_require__(/*! ./DialogBox.js */ 6);
// Netburner String helper functions
// Replaces the character at an index with a new character
function replaceAt(base, index, character) {
return base.substr(0, index) + character + base.substr(index + character.length);
}
exports.replaceAt = replaceAt;
/*
Converts a date representing time in milliseconds to a string with the format H hours M minutes and S seconds
e.g. 10000 -> "0 hours 0 minutes and 10 seconds"
120000 -> "0 0 hours 2 minutes and 0 seconds"
*/
function convertTimeMsToTimeElapsedString(time) {
const millisecondsPerSecond = 1000;
const secondPerMinute = 60;
const minutesPerHours = 60;
const secondPerHours = secondPerMinute * minutesPerHours;
const hoursPerDays = 24;
const secondPerDay = secondPerHours * hoursPerDays;
// Convert ms to seconds, since we only have second-level precision
const totalSeconds = Math.floor(time / millisecondsPerSecond);
const days = Math.floor(totalSeconds / secondPerDay);
const secTruncDays = totalSeconds % secondPerDay;
const hours = Math.floor(secTruncDays / secondPerHours);
const secTruncHours = secTruncDays % secondPerHours;
const minutes = Math.floor(secTruncHours / secondPerMinute);
const secTruncMinutes = secTruncHours % secondPerMinute;
const seconds = secTruncMinutes;
let res = "";
if (days) {
res += `${days} days `;
}
if (hours) {
res += `${hours} hours `;
}
if (minutes) {
res += `${minutes} minutes `;
}
res += `${seconds} seconds `;
return res;
}
exports.convertTimeMsToTimeElapsedString = convertTimeMsToTimeElapsedString;
// Finds the longest common starting substring in a set of strings
function longestCommonStart(strings) {
if (!containsAllStrings(strings)) {
return "";
}
if (strings.length == 0) {
return "";
}
const A = strings.concat().sort();
const a1 = A[0];
const a2 = A[A.length - 1];
const L = a1.length;
let i = 0;
while (i < L && a1.charAt(i).toLowerCase() === a2.charAt(i).toLowerCase()) {
i++;
}
return a1.substring(0, i);
}
exports.longestCommonStart = longestCommonStart;
// Returns whether a variable is a string
function isString(str) {
return (typeof str === "string" || str instanceof String);
}
exports.isString = isString;
// Returns whether an array contains entirely of string objects
function containsAllStrings(arr) {
return arr.every(isString);
}
exports.containsAllStrings = containsAllStrings;
// Formats a number with commas and a specific number of decimal digits
function formatNumber(num, numFractionDigits) {
return num.toLocaleString(undefined, {
maximumFractionDigits: numFractionDigits,
minimumFractionDigits: numFractionDigits,
});
}
exports.formatNumber = formatNumber;
// Count the number of times a substring occurs in a string
function numOccurrences(text, subString) {
text += "";
subString += "";
if (subString.length <= 0) {
return (text.length + 1);
}
let n = 0;
let pos = 0;
const step = subString.length;
while (true) {
pos = text.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
}
else {
break;
}
}
return n;
}
exports.numOccurrences = numOccurrences;
// Counters the number of Netscript operators in a string
function numNetscriptOperators(text) {
const total = numOccurrences(text, "+") +
numOccurrences(text, "-") +
numOccurrences(text, "*") +
numOccurrences(text, "/") +
numOccurrences(text, "%") +
numOccurrences(text, "&&") +
numOccurrences(text, "||") +
numOccurrences(text, "<") +
numOccurrences(text, ">") +
numOccurrences(text, "<=") +
numOccurrences(text, ">=") +
numOccurrences(text, "==") +
numOccurrences(text, "!=");
if (isNaN(total)) {
const message = "ERROR in counting number of operators in script. This is a bug, please report to game developer";
DialogBox_js_1.dialogBoxCreate(message, false);
return 0;
}
return total;
}
exports.numNetscriptOperators = numNetscriptOperators;
// Checks if a string contains HTML elements
function isHTML(str) {
const a = document.createElement("div");
a.innerHTML = str;
const c = a.childNodes;
for (let i = c.length; i--;) {
if (c[i].nodeType == 1) {
return true;
}
}
return false;
}
exports.isHTML = isHTML;
// Generates a random alphanumeric string with N characters
function generateRandomString(n) {
let str = "";
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < n; i++) {
str += chars.charAt(Math.floor(Math.random() * chars.length));
}
return str;
}
exports.generateRandomString = generateRandomString;
/***/ }),
/* 3 */
/*!**************************!*\
!*** ./src/Constants.js ***!
\**************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CONSTANTS", function() { return CONSTANTS; });
let CONSTANTS = {
Version: "0.39.0",
//Max level for any skill, assuming no multipliers. Determined by max numerical value in javascript for experience
//and the skill level formula in Player.js. Note that all this means it that when experience hits MAX_INT, then
//the player will have this level assuming no multipliers. Multipliers can cause skills to go above this.
MaxSkillLevel: 975,
//How much reputation is needed to join a megacorporation's faction
CorpFactionRepRequirement: 250000,
/* Base costs */
BaseCostFor1GBOfRamHome: 32000,
BaseCostFor1GBOfRamServer: 55000, //1 GB of RAM
BaseCostFor1GBOfRamHacknetNode: 30000,
TravelCost: 200000,
BaseCostForHacknetNode: 1000,
BaseCostForHacknetNodeCore: 500000,
/* Hacknet Node constants */
HacknetNodeMoneyGainPerLevel: 1.6,
HacknetNodePurchaseNextMult: 1.85, //Multiplier when purchasing an additional hacknet node
HacknetNodeUpgradeLevelMult: 1.04, //Multiplier for cost when upgrading level
HacknetNodeUpgradeRamMult: 1.28, //Multiplier for cost when upgrading RAM
HacknetNodeUpgradeCoreMult: 1.48, //Multiplier for cost when buying another core
HacknetNodeMaxLevel: 200,
HacknetNodeMaxRam: 64,
HacknetNodeMaxCores: 16,
/* Faction and Company favor */
FactionReputationToFavorBase: 500,
FactionReputationToFavorMult: 1.02,
CompanyReputationToFavorBase: 500,
CompanyReputationToFavorMult: 1.02,
/* Augmentation */
//NeuroFlux Governor cost multiplier as you level up
NeuroFluxGovernorLevelMult: 1.14,
/* Netscript Constants */
//RAM Costs for different commands
ScriptBaseRamCost: 1.6,
ScriptDomRamCost: 100,
ScriptWhileRamCost: 0,
ScriptForRamCost: 0,
ScriptIfRamCost: 0,
ScriptHackRamCost: 0.1,
ScriptGrowRamCost: 0.15,
ScriptWeakenRamCost: 0.15,
ScriptScanRamCost: 0.2,
ScriptPortProgramRamCost: 0.05,
ScriptRunRamCost: 1.0,
ScriptExecRamCost: 1.3,
ScriptSpawnRamCost: 2.0,
ScriptScpRamCost: 0.6,
ScriptKillRamCost: 0.5, //Kill and killall
ScriptHasRootAccessRamCost: 0.05,
ScriptGetHostnameRamCost: 0.05, //getHostname() and getIp()
ScriptGetHackingLevelRamCost: 0.05, //getHackingLevel()
ScriptGetMultipliersRamCost: 4.0, //getHackingMultipliers() and getBitNodeMultipliers()
ScriptGetServerRamCost: 0.1,
ScriptFileExistsRamCost: 0.1,
ScriptIsRunningRamCost: 0.1,
ScriptPurchaseHacknetRamCost: 1.5,
ScriptHacknetNodesRamCost: 4.0, //Base cost for accessing hacknet nodes array
ScriptHNUpgLevelRamCost: 0.4,
ScriptHNUpgRamRamCost: 0.6,
ScriptHNUpgCoreRamCost: 0.8,
ScriptGetStockRamCost: 2.0,
ScriptBuySellStockRamCost: 2.5,
ScriptPurchaseServerRamCost: 2.25,
ScriptRoundRamCost: 0.05,
ScriptReadWriteRamCost: 1.0,
ScriptArbScriptRamCost: 1.0, //Functions that apply to all scripts regardless of args
ScriptGetScriptRamCost: 0.1,
ScriptGetHackTimeRamCost: 0.05,
ScriptSingularityFn1RamCost: 1,
ScriptSingularityFn2RamCost: 2,
ScriptSingularityFn3RamCost: 3,
ScriptBladeburnerApiBaseRamCost: 4,
MultithreadingRAMCost: 1,
NumNetscriptPorts: 20,
//Server constants
ServerBaseGrowthRate: 1.03, //Unadjusted Growth rate
ServerMaxGrowthRate: 1.0035, //Maximum possible growth rate (max rate accounting for server security)
ServerFortifyAmount: 0.002, //Amount by which server's security increases when its hacked/grown
ServerWeakenAmount: 0.05, //Amount by which server's security decreases when weakened
PurchasedServerLimit: 25,
PurchasedServerMaxRam: 1048576, //2^20
//Augmentation Constants
AugmentationCostMultiplier: 5, //Used for balancing costs without having to readjust every Augmentation cost
AugmentationRepMultiplier: 2.5, //Used for balancing rep cost without having to readjust every value
MultipleAugMultiplier: 1.9,
//How much a TOR router costs
TorRouterCost: 200000,
//Infiltration constants
InfiltrationBribeBaseAmount: 100e3, //Amount per clearance level
InfiltrationMoneyValue: 3e3, //Convert "secret" value to money
InfiltrationRepValue: 1.4, //Convert "secret" value to faction reputation
//Stock market constants
WSEAccountCost: 200e6,
TIXAPICost: 5e9,
StockMarketCommission: 100e3,
//Hospital/Health
HospitalCostPerHp: 100e3,
//Intelligence-related constants
IntelligenceCrimeWeight: 0.05, //Weight for how much int affects crime success rates
IntelligenceInfiltrationWeight: 0.1, //Weight for how much int affects infiltration success rates
IntelligenceCrimeBaseExpGain: 0.001,
IntelligenceProgramBaseExpGain: 500, //Program required hack level divided by this to determine int exp gain
IntelligenceTerminalHackBaseExpGain: 200, //Hacking exp divided by this to determine int exp gain
IntelligenceSingFnBaseExpGain: 0.002,
IntelligenceClassBaseExpGain: 0.000001,
IntelligenceHackingMissionBaseExpGain: 0.03, //Hacking Mission difficulty multiplied by this to get exp gain
//Hacking Missions
HackingMissionRepToDiffConversion: 10000, //Faction rep is divided by this to get mission difficulty
HackingMissionRepToRewardConversion: 7, //Faction rep divided byt his to get mission rep reward
HackingMissionSpamTimeIncrease: 25000, //How much time limit increase is gained when conquering a Spam Node (ms)
HackingMissionTransferAttackIncrease: 1.05, //Multiplier by which the attack for all Core Nodes is increased when conquering a Transfer Node
HackingMissionMiscDefenseIncrease: 1.05, //The amount by which every misc node's defense is multiplied when one is conquered
HackingMissionDifficultyToHacking: 135, //Difficulty is multiplied by this to determine enemy's "hacking" level (to determine effects of scan/attack, etc)
HackingMissionHowToPlay: "Hacking missions are a minigame that, if won, will reward you with faction reputation.
" +
"In this game you control a set of Nodes and use them to try and defeat an enemy. Your Nodes " +
"are colored blue, while the enemy's are red. There are also other nodes on the map colored gray " +
"that initially belong to neither you nor the enemy. The goal of the game is " +
"to capture all of the enemy's Database nodes within the time limit. " +
"If you fail to do this, you will lose.
" +
"Each Node has three stats: Attack, Defense, and HP. There are five different actions that " +
"a Node can take:
" +
"Attack - Targets an enemy Node and lowers its HP. The effectiveness is determined by the owner's Attack, the Player's " +
"hacking level, and the enemy's defense.
" +
"Scan - Targets an enemy Node and lowers its Defense. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the " +
"enemy's defense.
" +
"Weaken - Targets an enemy Node and lowers its Attack. The effectiveness is determined by the owner's Attack, the Player's hacking level, and the enemy's " +
"defense.
" +
"Fortify - Raises the Node's Defense. The effectiveness is determined by your hacking level.
" +
"Overflow - Raises the Node's Attack but lowers its Defense. The effectiveness is determined by your hacking level.
" +
"Note that when determining the effectiveness of the above actions, the TOTAL Attack or Defense of the team is used, not just the " +
"Attack/Defense of the individual Node that is performing the action.
" +
"To capture a Node, you must lower its HP down to 0.
" +
"There are six different types of Nodes:
" +
"CPU Core - These are your main Nodes that are used to perform actions. Capable of performing every action
" +
"Firewall - Nodes with high defense. These Nodes can 'Fortify'
" +
"Database - A special type of Node. The player's objective is to conquer all of the enemy's Database Nodes within " +
"the time limit. These Nodes cannot perform any actions
" +
"Spam - Conquering one of these Nodes will slow the enemy's trace, giving the player additional time to complete " +
"the mission. These Nodes cannot perform any actions
" +
"Transfer - Conquering one of these nodes will increase the Attack of all of your CPU Cores by a small fixed percentage. " +
"These Nodes are capable of performing every action except the 'Attack' action
" +
"Shield - Nodes with high defense. These Nodes can 'Fortify'
" +
"To assign an action to a Node, you must first select one of your Nodes. This can be done by simply clicking on it. Double-clicking " +
"a node will select all of your Nodes of the same type (e.g. select all CPU Core Nodes or all Transfer Nodes). Note that only Nodes " +
"that can perform actions (CPU Core, Transfer, Shield, Firewall) can be selected. Selected Nodes will be denoted with a white highlight. After selecting a Node or multiple Nodes, " +
"select its action using the Action Buttons near the top of the screen. Every action also has a corresponding keyboard " +
"shortcut.
" +
"For certain actions such as attacking, scanning, and weakening, the Node performing the action must have a target. To target " +
"another node, simply click-and-drag from the 'source' Node to a target. A Node can only have one target, and you can target " +
"any Node that is adjacent to one of your Nodes (immediately above, below, or to the side. NOT diagonal). Furthermore, only CPU Cores and Transfer Nodes " +
"can target, since they are the only ones that can perform the related actions. To remove a target, you can simply click on the line that represents " +
"the connection between one of your Nodes and its target. Alternatively, you can select the 'source' Node and click the 'Drop Connection' button, " +
"or press 'd'.
" +
"Other Notes:
" +
"-Whenever a miscellenaous Node (not owned by the player or enemy) is conquered, the defense of all remaining miscellaneous Nodes that " +
"are not actively being targeted will increase by a fixed percentage.
" +
"-Whenever a Node is conquered, its stats are significantly reduced
" +
"-Miscellaneous Nodes slowly raise their defense over time
" +
"-Nodes slowly regenerate health over time.",
//Gang constants
GangRespectToReputationRatio: 2, //Respect is divided by this to get rep gain
MaximumGangMembers: 20,
GangRecruitCostMultiplier: 2,
GangTerritoryUpdateTimer: 150,
MillisecondsPer20Hours: 72000000,
GameCyclesPer20Hours: 72000000 / 200,
MillisecondsPer10Hours: 36000000,
GameCyclesPer10Hours: 36000000 / 200,
MillisecondsPer8Hours: 28800000,
GameCyclesPer8Hours: 28800000 / 200,
MillisecondsPer4Hours: 14400000,
GameCyclesPer4Hours: 14400000 / 200,
MillisecondsPer2Hours: 7200000,
GameCyclesPer2Hours: 7200000 / 200,
MillisecondsPerHour: 3600000,
GameCyclesPerHour: 3600000 / 200,
MillisecondsPerHalfHour: 1800000,
GameCyclesPerHalfHour: 1800000 / 200,
MillisecondsPerQuarterHour: 900000,
GameCyclesPerQuarterHour: 900000 / 200,
MillisecondsPerFiveMinutes: 300000,
GameCyclesPerFiveMinutes: 300000 / 200,
FactionWorkHacking: "Faction Hacking Work",
FactionWorkField: "Faction Field Work",
FactionWorkSecurity: "Faction Security Work",
WorkTypeCompany: "Working for Company",
WorkTypeCompanyPartTime: "Working for Company part-time",
WorkTypeFaction: "Working for Faction",
WorkTypeCreateProgram: "Working on Create a Program",
WorkTypeStudyClass: "Studying or Taking a class at university",
WorkTypeCrime: "Committing a crime",
ClassStudyComputerScience: "studying Computer Science",
ClassDataStructures: "taking a Data Structures course",
ClassNetworks: "taking a Networks course",
ClassAlgorithms: "taking an Algorithms course",
ClassManagement: "taking a Management course",
ClassLeadership: "taking a Leadership course",
ClassGymStrength: "training your strength at a gym",
ClassGymDefense: "training your defense at a gym",
ClassGymDexterity: "training your dexterity at a gym",
ClassGymAgility: "training your agility at a gym",
ClassDataStructuresBaseCost: 40,
ClassNetworksBaseCost: 80,
ClassAlgorithmsBaseCost: 320,
ClassManagementBaseCost: 160,
ClassLeadershipBaseCost: 320,
ClassGymBaseCost: 120,
CrimeSingFnDivider: 2, //Factor by which exp/profit is reduced when commiting crime through Sing Fn
CrimeShoplift: "shoplift",
CrimeRobStore: "rob a store",
CrimeMug: "mug someone",
CrimeLarceny: "commit larceny",
CrimeDrugs: "deal drugs",
CrimeBondForgery: "forge corporate bonds",
CrimeTraffickArms: "traffick illegal arms",
CrimeHomicide: "commit homicide",
CrimeGrandTheftAuto: "commit grand theft auto",
CrimeKidnap: "kidnap someone for ransom",
CrimeAssassination: "assassinate a high-profile target",
CrimeHeist: "pull off the ultimate heist",
/* Tutorial related things */
TutorialNetworkingText: "Servers are a central part of the game. You start with a single personal server (your home computer) " +
"and you can purchase additional servers as you progress through the game. Connecting to other servers " +
"and hacking them can be a major source of income and experience. Servers can also be used to run " +
"scripts which can automatically hack servers for you.
" +
"In order to navigate between machines, use the 'scan' or 'scan-analyze' Terminal command to see all servers " +
"that are reachable from your current server. Then, you can use the 'connect [hostname/ip]' " +
"command to connect to one of the available machines.
" +
"The 'hostname' and 'ifconfig' commands can be used to display the hostname/IP of the " +
"server you are currently connected to.",
TutorialHackingText: "In the year 2077, currency has become digital and decentralized. People and corporations " +
"store their money on servers. By hacking these servers, you can steal their money and gain " +
"experience.
" +
"
0;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
" +
"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 favour 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, "Bladeburners 2079", "More human than humans",
"In the middle of the 21st century, you were doing cutting-edge work at OmniTek Incorporated as part of the AI design team " +
"for advanced synthetic androids, or Synthoids for short. You helped achieve a major technological " +
"breakthrough in the sixth generation of the company's 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 API, which allows you to access Bladeburner " +
"functionality through Netscript. Furthermore:
" +
"The rank you gain from Bladeburner contracts/operations is reduced by 50%
" +
"Bladeburner skills cost twice as many skill points
" +
"Augmentations are 3x more expensive
" +
"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 7, 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 Bladeburner Netscript API in other " +
"BitNodes. In addition, this Source-File will increase all of your Bladeburner multipliers by:
" +
"Level 1: 8%
" +
"Level 2: 12%
" +
"Level 3: 14%");
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%");
BitNodes["BitNode12"] = new BitNode(12, "The Recursion", "Repeat.",
"To iterate is human, to recurse divine.
" +
"Every time this BitNode is destroyed, it becomes slightly harder. Destroying this BitNode will give your Souce-File 12, or " +
"if you already have this Source-File it will upgrade its level. There is no maximum level for Source-File 12. Each level " +
"of Source-File 12 will increase all of your multipliers by 1%.");
//Books: Frontera, Shiner
BitNodes["BitNode13"] = new BitNode(13, "fOS", "COMING SOON"); //Unlocks the new game mode and the rest of the BitNodes
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,
BladeburnerRank: 1,
BladeburnerSkillCost: 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.2;
BitNodeMultipliers.ServerStartingMoney = 0.2;
BitNodeMultipliers.ServerGrowthRate = 0.2;
BitNodeMultipliers.ScriptHackMoney = 0.2;
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 7: //Bladeburner 2079
BitNodeMultipliers.BladeburnerRank = 0.5;
BitNodeMultipliers.BladeburnerSkillCost = 2;
BitNodeMultipliers.AugmentationMoneyCost = 3;
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;
case 12: //The Recursion
let sf12Lvl = 0;
for (let i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles.length; i++) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles[i].n === 12) {
sf12Lvl = _Player_js__WEBPACK_IMPORTED_MODULE_0__["Player"].sourceFiles[i].lvl;
}
}
const inc = Math.pow(1.01, sf12Lvl);
const dec = Math.pow(0.99, sf12Lvl);
BitNodeMultipliers.HackingLevelMultiplier = dec;
BitNodeMultipliers.ServerMaxMoney = dec;
BitNodeMultipliers.ServerStartingMoney = dec;
BitNodeMultipliers.ServerGrowthRate = dec;
BitNodeMultipliers.ServerWeakenRate = dec;
//Does not scale, otherwise security might start at 300+
BitNodeMultipliers.ServerStartingSecurity = 1.5;
BitNodeMultipliers.ManualHackMoney = dec;
BitNodeMultipliers.ScriptHackMoney = dec;
BitNodeMultipliers.CompanyWorkMoney = dec;
BitNodeMultipliers.CrimeMoney = dec;
BitNodeMultipliers.HacknetNodeMoney = dec;
BitNodeMultipliers.CompanyWorkExpGain = dec;
BitNodeMultipliers.ClassGymExpGain = dec;
BitNodeMultipliers.FactionWorkExpGain = dec;
BitNodeMultipliers.HackExpGain = dec;
BitNodeMultipliers.CrimeExpGain = dec;
BitNodeMultipliers.FactionWorkRepGain = dec;
BitNodeMultipliers.FactionPassiveRepGain = dec;
BitNodeMultipliers.RepToDonateToFaction = inc;
BitNodeMultipliers.AugmentationRepCost = inc;
BitNodeMultipliers.AugmentationMoneyCost = inc;
BitNodeMultipliers.InfiltrationMoney = dec;
BitNodeMultipliers.InfiltrationRep = dec;
BitNodeMultipliers.CorporationValuation = dec;
default:
console.log("WARNING: Player.bitNodeN invalid");
break;
}
}
/***/ }),
/* 14 */
/*!****************************!*\
!*** ./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 */ 11);
/* 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;
}
/***/ }),
/* 15 */
/*!******************************!*\
!*** ./src/Augmentations.js ***!
\******************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AugmentationNames", function() { return AugmentationNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Augmentations", function() { return Augmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayerOwnedAugmentation", function() { return PlayerOwnedAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "installAugmentations", function() { return installAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initAugmentations", function() { return initAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "applyAugmentation", function() { return applyAugmentation; });
/* 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 */ 13);
/* 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 */ 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 */ 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 */ 11);
/* harmony import */ var _SourceFile_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./SourceFile.js */ 38);
/* 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 */ 7);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__);
//Augmentations
function Augmentation(params) {
if (params.name == null || params.info == null || params.moneyCost == null || params.repCost == null) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("ERROR Creating Augmentations. This is a bug please contact game dev");
return;
}
this.name = params.name;
this.info = params.info;
this.owned = false;
this.prereqs = params.prereqs ? params.prereqs : [];
//Price and reputation base requirements (can change based on faction multipliers)
this.baseRepRequirement = params.repCost * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost;
this.baseCost = params.moneyCost * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost;
//Level - Only applicable for some augmentations
// NeuroFlux Governor
this.level = 0;
}
//Takes in an array of faction names and adds this augmentation to all of those factions
Augmentation.prototype.addToFactions = function(factionList) {
for (var i = 0; i < factionList.length; ++i) {
var faction = _Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"][factionList[i]];
if (faction == null) {
throw new Error("In Augmentation.addToFactions(), could not find faction with this name:" + factionList[i]);
continue;
}
faction.augmentations.push(this.name);
}
}
Augmentation.prototype.addToAllFactions = function() {
for (var fac in _Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]) {
if (_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(fac)) {
var facObj = _Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"][fac];
if (facObj == null) {
console.log("ERROR: Invalid faction object");
continue;
}
facObj.augmentations.push(this.name);
}
}
}
Augmentation.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("Augmentation", this);
}
Augmentation.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(Augmentation, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.Augmentation = Augmentation;
let Augmentations = {}
function AddToAugmentations(aug) {
var name = aug.name;
Augmentations[name] = aug;
}
let AugmentationNames = {
Targeting1: "Augmented Targeting I",
Targeting2: "Augmented Targeting II",
Targeting3: "Augmented Targeting III",
SyntheticHeart: "Synthetic Heart",
SynfibrilMuscle: "Synfibril Muscle",
CombatRib1: "Combat Rib I",
CombatRib2: "Combat Rib II",
CombatRib3: "Combat Rib III",
NanofiberWeave: "Nanofiber Weave",
SubdermalArmor: "NEMEAN Subdermal Weave",
WiredReflexes: "Wired Reflexes",
GrapheneBoneLacings: "Graphene Bone Lacings",
BionicSpine: "Bionic Spine",
GrapheneBionicSpine: "Graphene Bionic Spine Upgrade",
BionicLegs: "Bionic Legs",
GrapheneBionicLegs: "Graphene Bionic Legs Upgrade",
SpeechProcessor: "Speech Processor Implant",
TITN41Injection: "TITN-41 Gene-Modification Injection",
EnhancedSocialInteractionImplant: "Enhanced Social Interaction Implant",
BitWire: "BitWire",
ArtificialBioNeuralNetwork: "Artificial Bio-neural Network Implant",
ArtificialSynapticPotentiation: "Artificial Synaptic Potentiation",
EnhancedMyelinSheathing: "Enhanced Myelin Sheathing",
SynapticEnhancement: "Synaptic Enhancement Implant",
NeuralRetentionEnhancement: "Neural-Retention Enhancement",
DataJack: "DataJack",
ENM: "Embedded Netburner Module",
ENMCore: "Embedded Netburner Module Core Implant",
ENMCoreV2: "Embedded Netburner Module Core V2 Upgrade",
ENMCoreV3: "Embedded Netburner Module Core V3 Upgrade",
ENMAnalyzeEngine: "Embedded Netburner Module Analyze Engine",
ENMDMA: "Embedded Netburner Module Direct Memory Access Upgrade",
Neuralstimulator: "Neuralstimulator",
NeuralAccelerator: "Neural Accelerator",
CranialSignalProcessorsG1: "Cranial Signal Processors - Gen I",
CranialSignalProcessorsG2: "Cranial Signal Processors - Gen II",
CranialSignalProcessorsG3: "Cranial Signal Processors - Gen III",
CranialSignalProcessorsG4: "Cranial Signal Processors - Gen IV",
CranialSignalProcessorsG5: "Cranial Signal Processors - Gen V",
NeuronalDensification: "Neuronal Densification",
NuoptimalInjectorImplant: "Nuoptimal Nootropic Injector Implant",
SpeechEnhancement: "Speech Enhancement",
FocusWire: "FocusWire",
PCDNI: "PC Direct-Neural Interface",
PCDNIOptimizer: "PC Direct-Neural Interface Optimization Submodule",
PCDNINeuralNetwork: "PC Direct-Neural Interface NeuroNet Injector",
ADRPheromone1: "ADR-V1 Pheromone Gene",
ADRPheromone2: "ADR-V2 Pheromone Gene",
HacknetNodeCPUUpload: "Hacknet Node CPU Architecture Neural-Upload",
HacknetNodeCacheUpload: "Hacknet Node Cache Architecture Neural-Upload",
HacknetNodeNICUpload: "Hacknet Node NIC Architecture Neural-Upload",
HacknetNodeKernelDNI: "Hacknet Node Kernel Direct-Neural Interface",
HacknetNodeCoreDNI: "Hacknet Node Core Direct-Neural Interface",
NeuroFluxGovernor: "NeuroFlux Governor",
Neurotrainer1: "Neurotrainer I",
Neurotrainer2: "Neurotrainer II",
Neurotrainer3: "Neurotrainer III",
Hypersight: "HyperSight Corneal Implant",
LuminCloaking1: "LuminCloaking-V1 Skin Implant",
LuminCloaking2: "LuminCloaking-V2 Skin Implant",
HemoRecirculator: "HemoRecirculator",
SmartSonar: "SmartSonar Implant",
PowerRecirculator: "Power Recirculation Core",
QLink: "QLink",
TheRedPill: "The Red Pill",
SPTN97: "SPTN-97 Gene Modification",
HiveMind: "ECorp HVMind Implant",
CordiARCReactor: "CordiARC Fusion Reactor",
SmartJaw: "SmartJaw",
Neotra: "Neotra",
Xanipher: "Xanipher",
nextSENS: "nextSENS Gene Modification",
OmniTekInfoLoad: "OmniTek InfoLoad",
PhotosyntheticCells: "Photosynthetic Cells",
Neurolink: "BitRunners Neurolink",
TheBlackHand: "The Black Hand",
CRTX42AA: "CRTX42-AA Gene Modification",
Neuregen: "Neuregen Gene Modification",
CashRoot: "CashRoot Starter Kit",
NutriGen: "NutriGen Implant",
INFRARet: "INFRARET Enhancement",
DermaForce: "DermaForce Particle Barrier",
GrapheneBrachiBlades: "Graphene BranchiBlades Upgrade",
GrapheneBionicArms: "Graphene Bionic Arms Upgrade",
BrachiBlades: "BrachiBlades",
BionicArms: "Bionic Arms",
SNA: "Social Negotiation Assistant (S.N.A)",
EsperEyewear: "EsperTech Bladeburner Eyewear",
EMS4Recombination: "EMS-4 Recombination",
OrionShoulder: "ORION-MKIV Shoulder",
HyperionV1: "Hyperion Plasma Cannon V1",
HyperionV2: "Hyperion Plasma Cannon V2",
GolemSerum: "GOLEM Serum",
VangelisVirus: "Vangelis Virus",
VangelisVirus3: "Vangelis Virus 3.0",
INTERLINKED: "I.N.T.E.R.L.I.N.K.E.D",
BladeRunner: "Blade's Runners",
BladeArmor: "BLADE-51b Tesla Armor",
BladeArmorPowerCells: "BLADE-51b Tesla Armor: Power Cells Upgrade",
BladeArmorEnergyShielding: "BLADE-51b Tesla Armor: Energy Shielding Upgrade",
BladeArmorUnibeam: "BLADE-51b Tesla Armor: Unibeam Upgrade",
BladeArmorOmnibeam: "BLADE-51b Tesla Armor: Omnibeam Upgrade",
BladeArmorIPU: "BLADE-51b Tesla Armor: IPU Upgrade",
BladesSimulacrum: "The Blade's Simulacrum",
//Wasteland Augs
//PepBoy: "P.E.P-Boy", Plasma Energy Projection System
//PepBoyForceField Generates plasma force fields
//PepBoyBlasts Generate high density plasma concussive blasts
//PepBoyDataStorage STore more data on pep boy,
}
function initAugmentations() {
for (var name in _Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]) {
if (_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"].hasOwnProperty(name)) {
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"][name].augmentations = [];
}
}
//Reset Augmentations
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["clearObject"])(Augmentations);
//Combat stat augmentations
var HemoRecirculator = new Augmentation({
name:AugmentationNames.HemoRecirculator, moneyCost: 9e6, repCost:4e3,
info:"A heart implant that greatly increases the body's ability to effectively use and pump " +
"blood.
This augmentation increases all of the player's combat stats by 8%."
});
HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]);
if (augmentationExists(AugmentationNames.HemoRecirculator)) {
delete Augmentations[AugmentationNames.HemoRecirculator];
}
AddToAugmentations(HemoRecirculator);
var Targeting1 = new Augmentation({
name:AugmentationNames.Targeting1, moneyCost:3e6, repCost:2e3,
info:"This cranial implant is embedded within the player's inner ear structure and optic nerves. It regulates and enhances the user's " +
"balance and hand-eye coordination. It is also capable of augmenting reality by projecting digital information " +
"directly onto the retina. These enhancements allow the player to better lock-on and keep track of enemies.
" +
"This augmentation increases the player's dexterity by 10%."
});
Targeting1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.Targeting1)) {
delete Augmentations[AugmentationNames.Targeting1];
}
AddToAugmentations(Targeting1);
var Targeting2 = new Augmentation({
name:AugmentationNames.Targeting2, moneyCost:8.5e6, repCost:3.5e3,
info:"This is an upgrade of the Augmented Targeting I cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.
This upgrade increases the player's dexterity " +
"by an additional 20%.",
prereqs:[AugmentationNames.Targeting1]
});
Targeting2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.Targeting2)) {
delete Augmentations[AugmentationNames.Targeting2];
}
AddToAugmentations(Targeting2);
var Targeting3 = new Augmentation({
name:AugmentationNames.Targeting3, moneyCost:23e6, repCost:11e3,
info:"This is an upgrade of the Augmented Targeting II cranial implant, which is capable of augmenting reality " +
"and enhances the user's balance and hand-eye coordination.
This upgrade increases the player's dexterity " +
"by an additional 30%.",
prereqs:[AugmentationNames.Targeting2]
});
Targeting3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(AugmentationNames.Targeting3)) {
delete Augmentations[AugmentationNames.Targeting3];
}
AddToAugmentations(Targeting3);
var SyntheticHeart = new Augmentation({
name:AugmentationNames.SyntheticHeart, moneyCost:575e6, repCost:300e3,
info:"This advanced artificial heart, created from plasteel and graphene, is capable of pumping more blood " +
"at much higher efficiencies than a normal human heart.
This augmentation increases the player's agility " +
"and strength by 50%"
});
SyntheticHeart.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati"]);
if (augmentationExists(AugmentationNames.SyntheticHeart)) {
delete Augmentations[AugmentationNames.SyntheticHeart];
}
AddToAugmentations(SyntheticHeart);
var SynfibrilMuscle = new Augmentation({
name:AugmentationNames.SynfibrilMuscle, repCost:175e3, moneyCost:225e6,
info:"The myofibrils in human muscles are injected with special chemicals that react with the proteins inside " +
"the myofibrils, altering their underlying structure. The end result is muscles that are stronger and more elastic. " +
"Scientists have named these artificially enhanced units 'synfibrils'.
This augmentation increases the player's " +
"strength and defense by 30%."
});
SynfibrilMuscle.addToFactions(["KuaiGong International", "Fulcrum Secret Technologies", "Speakers for the Dead",
"NWO", "The Covenant", "Daedalus", "Illuminati", "Blade Industries"]);
if (augmentationExists(AugmentationNames.SynfibrilMuscle)) {
delete Augmentations[AugmentationNames.SynfibrilMuscle];
}
AddToAugmentations(SynfibrilMuscle)
var CombatRib1 = new Augmentation({
name:AugmentationNames.CombatRib1, repCost:3e3, moneyCost:4750000,
info:"The human body's ribs are replaced with artificial ribs that automatically and continuously release cognitive " +
"and performance-enhancing drugs into the bloodstream, improving the user's abilities in combat.
" +
"This augmentation increases the player's strength and defense by 10%."
});
CombatRib1.addToFactions(["Slum Snakes", "The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.CombatRib1)) {
delete Augmentations[AugmentationNames.CombatRib1];
}
AddToAugmentations(CombatRib1);
var CombatRib2 = new Augmentation({
name:AugmentationNames.CombatRib2, repCost:7.5e3, moneyCost:13e6,
info:"This is an upgrade to the Combat Rib I augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream.
This upgrade increases the player's strength and defense by an additional 14%.",
prereqs:[AugmentationNames.CombatRib1]
});
CombatRib2.addToFactions(["The Dark Army", "The Syndicate", "Sector-12", "Volhaven", "Ishima",
"OmniTek Incorporated", "KuaiGong International", "Blade Industries"]);
if (augmentationExists(AugmentationNames.CombatRib2)) {
delete Augmentations[AugmentationNames.CombatRib2];
}
AddToAugmentations(CombatRib2);
var CombatRib3 = new Augmentation({
name:AugmentationNames.CombatRib3, repCost:14e3, moneyCost:24e6,
info:"This is an upgrade to the Combat Rib II augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream
. This upgrade increases the player's strength and defense by an additional 18%.",
prereqs:[AugmentationNames.CombatRib2],
});
CombatRib3.addToFactions(["The Dark Army", "The Syndicate", "OmniTek Incorporated",
"KuaiGong International", "Blade Industries", "The Covenant"]);
if (augmentationExists(AugmentationNames.CombatRib3)) {
delete Augmentations[AugmentationNames.CombatRib3];
}
AddToAugmentations(CombatRib3);
var NanofiberWeave = new Augmentation({
name:AugmentationNames.NanofiberWeave, repCost:15e3, moneyCost:25e6,
info:"Synthetic nanofibers are woven into the skin's extracellular matrix using electrospinning. " +
"This improves the skin's ability to regenerate itself and protect the body from external stresses and forces.
" +
"This augmentation increases the player's strength and defense by 20%."
});
NanofiberWeave.addToFactions(["Tian Di Hui", "The Syndicate", "The Dark Army", "Speakers for the Dead",
"Blade Industries", "Fulcrum Secret Technologies", "OmniTek Incorporated"]);
if (augmentationExists(AugmentationNames.NanofiberWeave)) {
delete Augmentations[AugmentationNames.NanofiberWeave];
}
AddToAugmentations(NanofiberWeave);
var SubdermalArmor = new Augmentation({
name:AugmentationNames.SubdermalArmor, repCost:350e3, moneyCost:650e6,
info:"The NEMEAN Subdermal Weave is a thin, light-weight, graphene plating that houses a dilatant fluid. " +
"The material is implanted underneath the skin, and is the most advanced form of defensive enhancement " +
"that has ever been created. The dilatant fluid, despite being thin and light, is extremely effective " +
"at stopping piercing blows and reducing blunt trauma. The properties of graphene allow the plating to " +
"mitigate damage from any fire-related or electrical traumas.
" +
"This augmentation increases the player's defense by 120%."
});
SubdermalArmor.addToFactions(["The Syndicate", "Fulcrum Secret Technologies", "Illuminati", "Daedalus",
"The Covenant"]);
if (augmentationExists(AugmentationNames.SubdermalArmor)) {
delete Augmentations[AugmentationNames.SubdermalArmor];
}
AddToAugmentations(SubdermalArmor);
var WiredReflexes = new Augmentation({
name:AugmentationNames.WiredReflexes, repCost:500, moneyCost:500e3,
info:"Synthetic nerve-enhancements are injected into all major parts of the somatic nervous system, " +
"supercharging the body's ability to send signals through neurons. This results in increased reflex speed.
" +
"This augmentation increases the player's agility and dexterity by 5%."
});
WiredReflexes.addToFactions(["Tian Di Hui", "Slum Snakes", "Sector-12", "Volhaven", "Aevum", "Ishima",
"The Syndicate", "The Dark Army", "Speakers for the Dead"]);
if (augmentationExists(AugmentationNames.WiredReflexes)) {
delete Augmentations[AugmentationNames.WiredReflexes];
}
AddToAugmentations(WiredReflexes);
var GrapheneBoneLacings = new Augmentation({
name:AugmentationNames.GrapheneBoneLacings, repCost:450e3, moneyCost:850e6,
info:"A graphene-based material is grafted and fused into the user's bones, significantly increasing " +
"their density and tensile strength.
" +
"This augmentation increases the player's strength and defense by 70%."
});
GrapheneBoneLacings.addToFactions(["Fulcrum Secret Technologies", "The Covenant"]);
if (augmentationExists(AugmentationNames.GrapheneBoneLacings)) {
delete Augmentations[AugmentationNames.GrapheneBoneLacings];
}
AddToAugmentations(GrapheneBoneLacings);
var BionicSpine = new Augmentation({
name:AugmentationNames.BionicSpine, repCost:18e3, moneyCost:25e6,
info:"An artificial spine created from plasteel and carbon fibers that completely replaces the organic spine. " +
"Not only is the Bionic Spine physically stronger than a human spine, but it is also capable of digitally " +
"stimulating and regulating the neural signals that are sent and received by the spinal cord. This results in " +
"greatly improved senses and reaction speeds.
" +
"This augmentation increases all of the player's combat stats by 15%."
});
BionicSpine.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(AugmentationNames.BionicSpine)) {
delete Augmentations[AugmentationNames.BionicSpine];
}
AddToAugmentations(BionicSpine);
var GrapheneBionicSpine = new Augmentation({
name:AugmentationNames.GrapheneBionicSpine, repCost:650e3, moneyCost:1200e6,
info:"An upgrade to the Bionic Spine augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.
" +
"This augmentation increases all of the player's combat stats by 60%.",
prereqs:[AugmentationNames.BionicSpine],
});
GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]);
if (augmentationExists(AugmentationNames.GrapheneBionicSpine)) {
delete Augmentations[AugmentationNames.GrapheneBionicSpine];
}
AddToAugmentations(GrapheneBionicSpine);
var BionicLegs = new Augmentation({
name:AugmentationNames.BionicLegs, repCost:60e3, moneyCost:75e6,
info:"Cybernetic legs created from plasteel and carbon fibers that completely replace the user's organic legs.
" +
"This augmentation increases the player's agility by 60%."
});
BionicLegs.addToFactions(["Speakers for the Dead", "The Syndicate", "KuaiGong International",
"OmniTek Incorporated", "Blade Industries"]);
if (augmentationExists(AugmentationNames.BionicLegs)) {
delete Augmentations[AugmentationNames.BionicLegs];
}
AddToAugmentations(BionicLegs);
var GrapheneBionicLegs = new Augmentation({
name:AugmentationNames.GrapheneBionicLegs, repCost:300e3, moneyCost:900e6,
info:"An upgrade to the Bionic Legs augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.
" +
"This augmentation increases the player's agility by an additional 150%.",
prereqs:[AugmentationNames.BionicLegs],
});
GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.GrapheneBionicLegs)) {
delete Augmentations[AugmentationNames.GrapheneBionicLegs];
}
AddToAugmentations(GrapheneBionicLegs);
//Labor stat augmentations
var SpeechProcessor = new Augmentation({
name:AugmentationNames.SpeechProcessor, repCost:3e3, moneyCost:10e6,
info:"A cochlear implant with an embedded computer that analyzes incoming speech. " +
"The embedded computer processes characteristics of incoming speech, such as tone " +
"and inflection, to pick up on subtle cues and aid in social interactions.
" +
"This augmentation increases the player's charisma by 20%."
});
SpeechProcessor.addToFactions(["Tian Di Hui", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Silhouette"]);
if (augmentationExists(AugmentationNames.SpeechProcessor)) {
delete Augmentations[AugmentationNames.SpeechProcessor];
}
AddToAugmentations(SpeechProcessor);
let TITN41Injection = new Augmentation({
name:AugmentationNames.TITN41Injection, repCost:10e3, moneyCost:38e6,
info:"TITN is a series of viruses that targets and alters the sequences of human DNA in genes that " +
"control personality. The TITN-41 strain alters these genes so that the subject becomes more " +
"outgoing and socialable.
" +
"This augmentation increases the player's charisma and charisma experience gain rate by 15%"
});
TITN41Injection.addToFactions(["Silhouette"]);
if (augmentationExists(AugmentationNames.TITN41Injection)) {
delete Augmentations[AugmentationNames.TITN41Injection];
}
AddToAugmentations(TITN41Injection);
var EnhancedSocialInteractionImplant = new Augmentation({
name:AugmentationNames.EnhancedSocialInteractionImplant, repCost:150e3, moneyCost:275e6,
info:"A cranial implant that greatly assists in the user's ability to analyze social situations " +
"and interactions. The system uses a wide variety of factors such as facial expression, body " +
"language, and the voice's tone/inflection to determine the best course of action during social" +
"situations. The implant also uses deep learning software to continuously learn new behavior" +
"patterns and how to best respond.
" +
"This augmentation increases the player's charisma and charisma experience gain rate by 60%."
});
EnhancedSocialInteractionImplant.addToFactions(["Bachman & Associates", "NWO", "Clarke Incorporated",
"OmniTek Incorporated", "Four Sigma"]);
if (augmentationExists(AugmentationNames.EnhancedSocialInteractionImplant)) {
delete Augmentations[AugmentationNames.EnhancedSocialInteractionImplant];
}
AddToAugmentations(EnhancedSocialInteractionImplant);
//Hacking augmentations
var BitWire = new Augmentation({
name:AugmentationNames.BitWire, repCost:1500, moneyCost:2e6,
info: "A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " +
"capabilities.
This augmentation increases the player's hacking skill by 5%"
});
BitWire.addToFactions(["CyberSec", "NiteSec"]);
if (augmentationExists(AugmentationNames.BitWire)) {
delete Augmentations[AugmentationNames.BitWire];
}
AddToAugmentations(BitWire);
var ArtificialBioNeuralNetwork = new Augmentation({
name:AugmentationNames.ArtificialBioNeuralNetwork, repCost:110e3, moneyCost:600e6,
info:"A network consisting of millions of nanoprocessors is embedded into the brain. " +
"The network is meant to mimick the way a biological brain solves a problem, which each " +
"nanoprocessor acting similar to the way a neuron would in a neural network. However, these " +
"nanoprocessors are programmed to perform computations much faster than organic neurons, " +
"allowing its user to solve much more complex problems at a much faster rate.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 3%
" +
"Increases the amount of money the player's gains from hacking by 15%
" +
"Increases the player's hacking skill by 12%"
});
ArtificialBioNeuralNetwork.addToFactions(["BitRunners", "Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.ArtificialBioNeuralNetwork)) {
delete Augmentations[AugmentationNames.ArtificialBioNeuralNetwork];
}
AddToAugmentations(ArtificialBioNeuralNetwork);
var ArtificialSynapticPotentiation = new Augmentation({
name:AugmentationNames.ArtificialSynapticPotentiation, repCost:2500, moneyCost:16e6,
info:"The body is injected with a chemical that artificially induces synaptic potentiation, " +
"otherwise known as the strengthening of synapses. This results in a enhanced cognitive abilities.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 2%
" +
"Increases the player's hacking chance by 5%
" +
"Increases the player's hacking experience gain rate by 5%"
});
ArtificialSynapticPotentiation.addToFactions(["The Black Hand", "NiteSec"]);
if (augmentationExists(AugmentationNames.ArtificialSynapticPotentiation)) {
delete Augmentations[AugmentationNames.ArtificialSynapticPotentiation];
}
AddToAugmentations(ArtificialSynapticPotentiation);
var EnhancedMyelinSheathing = new Augmentation({
name:AugmentationNames.EnhancedMyelinSheathing, repCost:40e3, moneyCost:275e6,
info:"Electrical signals are used to induce a new, artificial form of myelinogensis in the human body. " +
"This process results in the proliferation of new, synthetic myelin sheaths in the nervous " +
"system. These myelin sheaths can propogate neuro-signals much faster than their organic " +
"counterparts, leading to greater processing speeds and better brain function.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 3%
" +
"Increases the player's hacking skill by 8%
" +
"Increases the player's hacking experience gain rate by 10%"
});
EnhancedMyelinSheathing.addToFactions(["Fulcrum Secret Technologies", "BitRunners", "The Black Hand"]);
if (augmentationExists(AugmentationNames.EnhancedMyelinSheathing)) {
delete Augmentations[AugmentationNames.EnhancedMyelinSheathing];
}
AddToAugmentations(EnhancedMyelinSheathing);
var SynapticEnhancement = new Augmentation({
name:AugmentationNames.SynapticEnhancement, repCost:800, moneyCost:1.5e6,
info:"A small cranial implant that continuously uses weak electric signals to stimulate the brain and " +
"induce stronger synaptic activity. This improves the user's cognitive abilities.
" +
"This augmentation increases the player's hacking speed by 3%."
});
SynapticEnhancement.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.SynapticEnhancement)) {
delete Augmentations[AugmentationNames.SynapticEnhancement];
}
AddToAugmentations(SynapticEnhancement);
var NeuralRetentionEnhancement = new Augmentation({
name:AugmentationNames.NeuralRetentionEnhancement, repCost:8e3, moneyCost:50e6,
info:"Chemical injections are used to permanently alter and strengthen the brain's neuronal " +
"circuits, strengthening its ability to retain information.
" +
"This augmentation increases the player's hacking experience gain rate by 25%."
});
NeuralRetentionEnhancement.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.NeuralRetentionEnhancement)) {
delete Augmentations[AugmentationNames.NeuralRetentionEnhancement];
}
AddToAugmentations(NeuralRetentionEnhancement);
var DataJack = new Augmentation({
name:AugmentationNames.DataJack, repCost:45e3, moneyCost:90e6,
info:"A brain implant that provides an interface for direct, wireless communication between a computer's main " +
"memory and the mind. This implant allows the user to not only access a computer's memory, but also alter " +
"and delete it.
" +
"This augmentation increases the amount of money the player gains from hacking by 25%"
});
DataJack.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "Chongqing", "New Tokyo"]);
if (augmentationExists(AugmentationNames.DataJack)) {
delete Augmentations[AugmentationNames.DataJack];
}
AddToAugmentations(DataJack);
var ENM = new Augmentation({
name:AugmentationNames.ENM, repCost:6e3, moneyCost:50e6,
info:"A thin device embedded inside the arm containing a wireless module capable of connecting " +
"to nearby networks. Once connected, the Netburner Module is capable of capturing and " +
"processing all of the traffic on that network. By itself, the Embedded Netburner Module does " +
"not do much, but a variety of very powerful upgrades can be installed that allow you to fully " +
"control the traffic on a network.
" +
"This augmentation increases the player's hacking skill by 8%"
});
ENM.addToFactions(["BitRunners", "The Black Hand", "NiteSec", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(AugmentationNames.ENM)) {
delete Augmentations[AugmentationNames.ENM];
}
AddToAugmentations(ENM);
var ENMCore = new Augmentation({
name:AugmentationNames.ENMCore, repCost:100e3, moneyCost:500e6,
info:"The Core library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgrade allows the Embedded Netburner Module to generate its own data on a network.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 3%
" +
"Increases the amount of money the player gains from hacking by 10%
" +
"Increases the player's chance of successfully performing a hack by 3%
" +
"Increases the player's hacking experience gain rate by 7%
" +
"Increases the player's hacking skill by 7%",
prereqs:[AugmentationNames.ENM]
});
ENMCore.addToFactions(["BitRunners", "The Black Hand", "ECorp", "MegaCorp",
"Fulcrum Secret Technologies", "NWO", "Blade Industries"]);
if (augmentationExists(AugmentationNames.ENMCore)) {
delete Augmentations[AugmentationNames.ENMCore];
}
AddToAugmentations(ENMCore);
var ENMCoreV2 = new Augmentation({
name:AugmentationNames.ENMCoreV2, repCost:400e3, moneyCost:900e6,
info:"The Core V2 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to control the information on " +
"a network by re-routing traffic, spoofing IP addresses, or altering the data inside network " +
"packets.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 5%
" +
"Increases the amount of money the player gains from hacking by 30%
" +
"Increases the player's chance of successfully performing a hack by 5%
" +
"Increases the player's hacking experience gain rate by 15%
" +
"Increases the player's hacking skill by 8%",
prereqs:[AugmentationNames.ENMCore]
});
ENMCoreV2.addToFactions(["BitRunners", "ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Blade Industries", "OmniTek Incorporated", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.ENMCoreV2)) {
delete Augmentations[AugmentationNames.ENMCoreV2];
}
AddToAugmentations(ENMCoreV2);
var ENMCoreV3 = new Augmentation({
name:AugmentationNames.ENMCoreV3, repCost:700e3, moneyCost:1500e6,
info:"The Core V3 library is an implant that upgrades the firmware of the Embedded Netburner Module. " +
"This upgraded firmware allows the Embedded Netburner Module to seamlessly inject code into " +
"any device on a network.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 5%
" +
"Increases the amount of money the player gains from hacking by 40%
" +
"Increases the player's chance of successfully performing a hack by 10%
" +
"Increases the player's hacking experience gain rate by 25%
" +
"Increases the player's hacking skill by 10%",
prereqs:[AugmentationNames.ENMCoreV2],
});
ENMCoreV3.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMCoreV3)) {
delete Augmentations[AugmentationNames.ENMCoreV3];
}
AddToAugmentations(ENMCoreV3);
var ENMAnalyzeEngine = new Augmentation({
name:AugmentationNames.ENMAnalyzeEngine, repCost:250e3, moneyCost:1200e6,
info:"Installs the Analyze Engine for the Embedded Netburner Module, which is a CPU cluster " +
"that vastly outperforms the Netburner Module's native single-core processor.
" +
"This augmentation increases the player's hacking speed by 10%.",
prereqs:[AugmentationNames.ENM],
});
ENMAnalyzeEngine.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMAnalyzeEngine)) {
delete Augmentations[AugmentationNames.ENMAnalyzeEngine];
}
AddToAugmentations(ENMAnalyzeEngine);
var ENMDMA = new Augmentation({
name:AugmentationNames.ENMDMA, repCost:400e3, moneyCost:1400e6,
info:"This implant installs a Direct Memory Access (DMA) controller into the " +
"Embedded Netburner Module. This allows the Module to send and receive data " +
"directly to and from the main memory of devices on a network.
" +
"This augmentation:
" +
"Increases the amount of money the player gains from hacking by 40%
" +
"Increases the player's chance of successfully performing a hack by 20%",
prereqs:[AugmentationNames.ENM],
});
ENMDMA.addToFactions(["ECorp", "MegaCorp", "Fulcrum Secret Technologies", "NWO",
"Daedalus", "The Covenant", "Illuminati"]);
if (augmentationExists(AugmentationNames.ENMDMA)) {
delete Augmentations[AugmentationNames.ENMDMA];
}
AddToAugmentations(ENMDMA);
var Neuralstimulator = new Augmentation({
name:AugmentationNames.Neuralstimulator, repCost:20e3, moneyCost:600e6,
info:"A cranial implant that intelligently stimulates certain areas of the brain " +
"in order to improve cognitive functions
" +
"This augmentation:
" +
"Increases the player's hacking speed by 2%
" +
"Increases the player's chance of successfully performing a hack by 10%
" +
"Increases the player's hacking experience gain rate by 12%"
});
Neuralstimulator.addToFactions(["The Black Hand", "Chongqing", "Sector-12", "New Tokyo", "Aevum",
"Ishima", "Volhaven", "Bachman & Associates", "Clarke Incorporated",
"Four Sigma"]);
if (augmentationExists(AugmentationNames.Neuralstimulator)) {
delete Augmentations[AugmentationNames.Neuralstimulator];
}
AddToAugmentations(Neuralstimulator);
var NeuralAccelerator = new Augmentation({
name:AugmentationNames.NeuralAccelerator, repCost:80e3, moneyCost:350e6,
info:"A microprocessor that accelerates the processing " +
"speed of biological neural networks. This is a cranial implant that is embedded inside the brain.
" +
"This augmentation:
" +
"Increases the player's hacking skill by 10%
" +
"Increases the player's hacking experience gain rate by 15%
" +
"Increases the amount of money the player gains from hacking by 20%"
});
NeuralAccelerator.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.NeuralAccelerator)) {
delete Augmentations[AugmentationNames.NeuralAccelerator];
}
AddToAugmentations(NeuralAccelerator);
var CranialSignalProcessorsG1 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG1, repCost:4e3, moneyCost:14e6,
info:"The first generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 1%
" +
"Increases the player's hacking skill by 5%"
});
CranialSignalProcessorsG1.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG1)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG1];
}
AddToAugmentations(CranialSignalProcessorsG1);
var CranialSignalProcessorsG2 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG2, repCost:7500, moneyCost:25e6,
info:"The second generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 2%
" +
"Increases the player's chance of successfully performing a hack by 5%
" +
"Increases the player's hacking skill by 7%"
});
CranialSignalProcessorsG2.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG2)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG2];
}
AddToAugmentations(CranialSignalProcessorsG2);
var CranialSignalProcessorsG3 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG3, repCost:20e3, moneyCost:110e6,
info:"The third generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 2%
" +
"Increases the amount of money the player gains from hacking by 15%
" +
"Increases the player's hacking skill by 9%"
});
CranialSignalProcessorsG3.addToFactions(["NiteSec", "The Black Hand"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG3)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG3];
}
AddToAugmentations(CranialSignalProcessorsG3);
var CranialSignalProcessorsG4 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG4, repCost:50e3, moneyCost:220e6,
info:"The fourth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 2%
" +
"Increases the amount of money the player gains from hacking by 20%
" +
"Increases the amount of money the player can inject into servers using grow() by 25%"
});
CranialSignalProcessorsG4.addToFactions(["The Black Hand"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG4)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG4];
}
AddToAugmentations(CranialSignalProcessorsG4);
var CranialSignalProcessorsG5 = new Augmentation({
name:AugmentationNames.CranialSignalProcessorsG5, repCost:100e3, moneyCost:450e6,
info:"The fifth generation of Cranial Signal Processors. Cranial Signal Processors " +
"are a set of specialized microprocessors that are attached to " +
"neurons in the brain. These chips process neural signals to quickly and automatically perform specific computations " +
"so that the brain doesn't have to.
" +
"This augmentation:
" +
"Increases the player's hacking skill by 30%
" +
"Increases the amount of money the player gains from hacking by 25%
" +
"Increases the amount of money the player can inject into servers using grow() by 75%"
});
CranialSignalProcessorsG5.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.CranialSignalProcessorsG5)) {
delete Augmentations[AugmentationNames.CranialSignalProcessorsG5];
}
AddToAugmentations(CranialSignalProcessorsG5);
var NeuronalDensification = new Augmentation({
name:AugmentationNames.NeuronalDensification, repCost:75e3, moneyCost:275e6,
info:"The brain is surgically re-engineered to have increased neuronal density " +
"by decreasing the neuron gap junction. Then, the body is genetically modified " +
"to enhance the production and capabilities of its neural stem cells.
" +
"This augmentation:
" +
"Increases the player's hacking skill by 15%
" +
"Increases the player's hacking experience gain rate by 10%
"+
"Increases the player's hacking speed by 3%"
});
NeuronalDensification.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.NeuronalDensification)) {
delete Augmentations[AugmentationNames.NeuronalDensification];
}
AddToAugmentations(NeuronalDensification);
//Work Augmentations
var NuoptimalInjectorImplant = new Augmentation({
name:AugmentationNames.NuoptimalInjectorImplant, repCost:2e3, moneyCost:4e6,
info:"This torso implant automatically injects nootropic supplements into " +
"the bloodstream to improve memory, increase focus, and provide other " +
"cognitive enhancements.
" +
"This augmentation increases the amount of reputation the player gains " +
"when working for a company by 20%."
});
NuoptimalInjectorImplant.addToFactions(["Tian Di Hui", "Volhaven", "New Tokyo", "Chongqing", "Ishima",
"Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
if (augmentationExists(AugmentationNames.NuoptimalInjectorImplant)) {
delete Augmentations[AugmentationNames.NuoptimalInjectorImplant];
}
AddToAugmentations(NuoptimalInjectorImplant);
var SpeechEnhancement = new Augmentation({
name:AugmentationNames.SpeechEnhancement, repCost:1e3, moneyCost:2.5e6,
info:"An advanced neural implant that improves your speaking abilities, making " +
"you more convincing and likable in conversations and overall improving your " +
"social interactions.
" +
"This augmentation:
" +
"Increases the player's charisma by 10%
" +
"Increases the amount of reputation the player gains when working for a company by 10%"
});
SpeechEnhancement.addToFactions(["Tian Di Hui", "Speakers for the Dead", "Four Sigma", "KuaiGong International",
"Clarke Incorporated", "Four Sigma", "Bachman & Associates"]);
if (augmentationExists(AugmentationNames.SpeechEnhancement)) {
delete Augmentations[AugmentationNames.SpeechEnhancement];
}
AddToAugmentations(SpeechEnhancement);
var FocusWire = new Augmentation({
name:AugmentationNames.FocusWire, repCost:30e3, moneyCost:180e6,
info:"A cranial implant that stops procrastination by blocking specific neural pathways " +
"in the brain.
" +
"This augmentation:
" +
"Increases all experience gains by 5%
" +
"Increases the amount of money the player gains from working by 20%
" +
"Increases the amount of reputation the player gains when working for a company by 10%"
});
FocusWire.addToFactions(["Bachman & Associates", "Clarke Incorporated", "Four Sigma", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.FocusWire)) {
delete Augmentations[AugmentationNames.FocusWire];
}
AddToAugmentations(FocusWire)
var PCDNI = new Augmentation({
name:AugmentationNames.PCDNI, repCost:150e3, moneyCost:750e6,
info:"Installs a Direct-Neural Interface jack into your arm that is compatible with most " +
"computers. Connecting to a computer through this jack allows you to interface with " +
"it using the brain's electrochemical signals.
" +
"This augmentation:
" +
"Increases the amount of reputation the player gains when working for a company by 30%
" +
"Increases the player's hacking skill by 8%"
});
PCDNI.addToFactions(["Four Sigma", "OmniTek Incorporated", "ECorp", "Blade Industries"]);
if (augmentationExists(AugmentationNames.PCDNI)) {
delete Augmentations[AugmentationNames.PCDNI];
}
AddToAugmentations(PCDNI);
var PCDNIOptimizer = new Augmentation({
name:AugmentationNames.PCDNIOptimizer, repCost:200e3, moneyCost:900e6,
info:"This is a submodule upgrade to the PC Direct-Neural Interface augmentation. It " +
"improves the performance of the interface and gives the user more control options " +
"to the connected computer.
" +
"This augmentation:
" +
"Increases the amount of reputation the player gains when working for a company by 75%
" +
"Increases the player's hacking skill by 10%",
prereqs:[AugmentationNames.PCDNI],
});
PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
if (augmentationExists(AugmentationNames.PCDNIOptimizer)) {
delete Augmentations[AugmentationNames.PCDNIOptimizer];
}
AddToAugmentations(PCDNIOptimizer);
var PCDNINeuralNetwork = new Augmentation({
name:AugmentationNames.PCDNINeuralNetwork, repCost:600e3, moneyCost:1500e6,
info:"This is an additional installation that upgrades the functionality of the " +
"PC Direct-Neural Interface augmentation. When connected to a computer, " +
"The NeuroNet Injector upgrade allows the user to use his/her own brain's " +
"processing power to aid the computer in computational tasks.
" +
"This augmentation:
" +
"Increases the amount of reputation the player gains when working for a company by 100%
" +
"Increases the player's hacking skill by 10%
" +
"Increases the player's hacking speed by 5%",
prereqs:[AugmentationNames.PCDNI],
});
PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.PCDNINeuralNetwork)) {
delete Augmentations[AugmentationNames.PCDNINeuralNetwork];
}
AddToAugmentations(PCDNINeuralNetwork);
var ADRPheromone1 = new Augmentation({
name:AugmentationNames.ADRPheromone1, repCost:1500, moneyCost:3.5e6,
info:"The body is genetically re-engineered so that it produces the ADR-V1 pheromone, " +
"an artificial pheromone discovered by scientists. The ADR-V1 pheromone, when excreted, " +
"triggers feelings of admiration and approval in other people.
" +
"This augmentation:
" +
"Increases the amount of reputation the player gains when working for a company by 10%
" +
"Increases the amount of reputation the player gains for a faction by 10%"
});
ADRPheromone1.addToFactions(["Tian Di Hui", "The Syndicate", "NWO", "MegaCorp", "Four Sigma"]);
if (augmentationExists(AugmentationNames.ADRPheromone1)) {
delete Augmentations[AugmentationNames.ADRPheromone1];
}
AddToAugmentations(ADRPheromone1);
var ADRPheromone2 = new Augmentation({
name:AugmentationNames.ADRPheromone2, repCost:25e3, moneyCost:110e6,
info:"The body is genetically re-engineered so that it produces the ADR-V2 pheromone, " +
"which is similar to but more potent than ADR-V1. This pheromone, when excreted, " +
"triggers feelings of admiration, approval, and respect in others.
" +
"This augmentation:
" +
"Increases the amount of reputation the player gains for a faction and company by 20%."
});
ADRPheromone2.addToFactions(["Silhouette", "Four Sigma", "Bachman & Associates", "Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.ADRPheromone2)) {
delete Augmentations[AugmentationNames.ADRPheromone2];
}
AddToAugmentations(ADRPheromone2);
//HacknetNode Augmentations
var HacknetNodeCPUUpload = new Augmentation({
name:AugmentationNames.HacknetNodeCPUUpload, repCost:1500, moneyCost:2.2e6,
info:"Uploads the architecture and design details of a Hacknet Node's CPU into " +
"the brain. This allows the user to engineer custom hardware and software " +
"for the Hacknet Node that provides better performance.
" +
"This augmentation:
" +
"Increases the amount of money produced by Hacknet Nodes by 15%
" +
"Decreases the cost of purchasing a Hacknet Node by 15%"
});
HacknetNodeCPUUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCPUUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeCPUUpload];
}
AddToAugmentations(HacknetNodeCPUUpload);
var HacknetNodeCacheUpload = new Augmentation({
name:AugmentationNames.HacknetNodeCacheUpload, repCost:1e3, moneyCost:1.1e6,
info:"Uploads the architecture and design details of a Hacknet Node's main-memory cache " +
"into the brain. This allows the user to engineer custom cache hardware for the " +
"Hacknet Node that offers better performance.
" +
"This augmentation:
" +
"Increases the amount of money produced by Hacknet Nodes by 10%
" +
"Decreases the cost of leveling up a Hacknet Node by 15%"
});
HacknetNodeCacheUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCacheUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeCacheUpload];
}
AddToAugmentations(HacknetNodeCacheUpload);
var HacknetNodeNICUpload = new Augmentation({
name:AugmentationNames.HacknetNodeNICUpload, repCost:750, moneyCost:900e3,
info:"Uploads the architecture and design details of a Hacknet Node's Network Interface Card (NIC) " +
"into the brain. This allows the user to engineer a custom NIC for the Hacknet Node that " +
"offers better performance.
" +
"This augmentation:
" +
"Increases the amount of money produced by Hacknet Nodes by 10%
" +
"Decreases the cost of purchasing a Hacknet Node by 10%"
});
HacknetNodeNICUpload.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeNICUpload)) {
delete Augmentations[AugmentationNames.HacknetNodeNICUpload];
}
AddToAugmentations(HacknetNodeNICUpload);
var HacknetNodeKernelDNI = new Augmentation({
name:AugmentationNames.HacknetNodeKernelDNI, repCost:3e3, moneyCost:8e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting to a " +
"Hacknet Node. This lets the user access and manipulate the Node's kernel using the mind's " +
"electrochemical signals.
" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 25%."
});
HacknetNodeKernelDNI.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeKernelDNI)) {
delete Augmentations[AugmentationNames.HacknetNodeKernelDNI];
}
AddToAugmentations(HacknetNodeKernelDNI);
var HacknetNodeCoreDNI = new Augmentation({
name:AugmentationNames.HacknetNodeCoreDNI, repCost:5e3, moneyCost:12e6,
info:"Installs a Direct-Neural Interface jack into the arm that is capable of connecting " +
"to a Hacknet Node. This lets the user access and manipulate the Node's processing logic using " +
"the mind's electrochemical signals.
" +
"This augmentation increases the amount of money produced by Hacknet Nodes by 45%."
});
HacknetNodeCoreDNI.addToFactions(["Netburners"]);
if (augmentationExists(AugmentationNames.HacknetNodeCoreDNI)) {
delete Augmentations[AugmentationNames.HacknetNodeCoreDNI];
}
AddToAugmentations(HacknetNodeCoreDNI);
//Misc/Hybrid augmentations
var NeuroFluxGovernor = new Augmentation({
name:AugmentationNames.NeuroFluxGovernor, repCost:500, moneyCost: 750e3,
info:"A device that is embedded in the back of the neck. The NeuroFlux Governor " +
"monitors and regulates nervous impulses coming to and from the spinal column, " +
"essentially 'governing' the body. By doing so, it improves the functionality of the " +
"body's nervous system.
" +
"This is a special augmentation because it can be leveled up infinitely. Each level of this augmentation " +
"increases ALL of the player's multipliers by 1%"
});
var nextLevel = Object(_Faction_js__WEBPACK_IMPORTED_MODULE_3__["getNextNeurofluxLevel"])();
NeuroFluxGovernor.level = nextLevel - 1;
mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].NeuroFluxGovernorLevelMult, NeuroFluxGovernor.level);
NeuroFluxGovernor.baseRepRequirement = 500 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationRepMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationRepCost;
NeuroFluxGovernor.baseCost = 750e3 * mult * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].AugmentationCostMultiplier * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].AugmentationMoneyCost;
if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) {
delete Augmentations[AugmentationNames.NeuroFluxGovernor];
}
NeuroFluxGovernor.addToAllFactions();
AddToAugmentations(NeuroFluxGovernor);
var Neurotrainer1 = new Augmentation({
name:AugmentationNames.Neurotrainer1, repCost:400, moneyCost:800e3,
info:"A decentralized cranial implant that improves the brain's ability to learn. It is " +
"installed by releasing millions of nanobots into the human brain, each of which " +
"attaches to a different neural pathway to enhance the brain's ability to retain " +
"and retrieve information.
" +
"This augmentation increases the player's experience gain rate for all stats by 10%"
});
Neurotrainer1.addToFactions(["CyberSec"]);
if (augmentationExists(AugmentationNames.Neurotrainer1)) {
delete Augmentations[AugmentationNames.Neurotrainer1];
}
AddToAugmentations(Neurotrainer1);
var Neurotrainer2 = new Augmentation({
name:AugmentationNames.Neurotrainer2, repCost:4e3, moneyCost:9e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I augmentation, but it does not " +
"require Neurotrainer I to be installed as a prerequisite.
" +
"This augmentation increases the player's experience gain rate for all stats by 15%"
});
Neurotrainer2.addToFactions(["BitRunners", "NiteSec"]);
if (augmentationExists(AugmentationNames.Neurotrainer2)) {
delete Augmentations[AugmentationNames.Neurotrainer2];
}
AddToAugmentations(Neurotrainer2);
var Neurotrainer3 = new Augmentation({
name:AugmentationNames.Neurotrainer3, repCost:10e3, moneyCost:26e6,
info:"A decentralized cranial implant that improves the brain's ability to learn. This " +
"is a more powerful version of the Neurotrainer I and Neurotrainer II augmentation, " +
"but it does not require either of them to be installed as a prerequisite.
" +
"This augmentation increases the player's experience gain rate for all stats by 20%"
});
Neurotrainer3.addToFactions(["NWO", "Four Sigma"]);
if (augmentationExists(AugmentationNames.Neurotrainer3)) {
delete Augmentations[AugmentationNames.Neurotrainer3];
}
AddToAugmentations(Neurotrainer3);
var Hypersight = new Augmentation({
name:AugmentationNames.Hypersight, repCost:60e3, moneyCost:550e6,
info:"A bionic eye implant that grants sight capabilities far beyond those of a natural human. " +
"Embedded circuitry within the implant provides the ability to detect heat and movement " +
"through solid objects such as wells, thus providing 'x-ray vision'-like capabilities.
" +
"This augmentation:
" +
"Increases the player's dexterity by 40%
" +
"Increases the player's hacking speed by 3%
" +
"Increases the amount of money the player gains from hacking by 10%"
});
Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.Hypersight)) {
delete Augmentations[AugmentationNames.Hypersight];
}
AddToAugmentations(Hypersight);
var LuminCloaking1 = new Augmentation({
name:AugmentationNames.LuminCloaking1, repCost:600, moneyCost:1e6,
info:"A skin implant that reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, have a negative refractive index. As a result, they bend light " +
"around the skin, making the user much harder to see from the naked eye.
" +
"This augmentation:
" +
"Increases the player's agility by 5%
" +
"Increases the amount of money the player gains from crimes by 10%"
});
LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking1)) {
delete Augmentations[AugmentationNames.LuminCloaking1];
}
AddToAugmentations(LuminCloaking1);
var LuminCloaking2 = new Augmentation({
name:AugmentationNames.LuminCloaking2, repCost:2e3, moneyCost:6e6,
info:"This is a more advanced version of the LuminCloaking-V2 augmentation. This skin implant " +
"reinforces the skin with highly-advanced synthetic cells. These " +
"cells, when powered, are capable of not only bending light but also of bending heat, " +
"making the user more resilient as well as stealthy.
" +
"This augmentation:
" +
"Increases the player's agility by 10%
" +
"Increases the player's defense by 10%
" +
"Increases the amount of money the player gains from crimes by 25%"
});
LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking2)) {
delete Augmentations[AugmentationNames.LuminCloaking2];
}
AddToAugmentations(LuminCloaking2);
var SmartSonar = new Augmentation({
name:AugmentationNames.SmartSonar, repCost:9e3, moneyCost:15e6,
info:"A cochlear implant that helps the player detect and locate enemies " +
"using sound propagation.
" +
"This augmentation:
" +
"Increases the player's dexterity by 10%
" +
"Increases the player's dexterity experience gain rate by 15%
" +
"Increases the amount of money the player gains from crimes by 25%"
});
SmartSonar.addToFactions(["Slum Snakes"]);
if (augmentationExists(AugmentationNames.SmartSonar)) {
delete Augmentations[AugmentationNames.SmartSonar];
}
AddToAugmentations(SmartSonar);
var PowerRecirculator = new Augmentation({
name:AugmentationNames.PowerRecirculator, repCost:10e3, moneyCost:36e6,
info:"The body's nerves are attached with polypyrrole nanocircuits that " +
"are capable of capturing wasted energy (in the form of heat) " +
"and converting it back into usable power.
" +
"This augmentation:
" +
"Increases all of the player's stats by 5%
" +
"Increases the player's experience gain rate for all stats by 10%"
});
PowerRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate", "NWO"]);
if (augmentationExists(AugmentationNames.PowerRecirculator)) {
delete Augmentations[AugmentationNames.PowerRecirculator];
}
AddToAugmentations(PowerRecirculator);
//Unique AUGS (Each Faction gets one unique augmentation)
//Factions that already have unique augs up to this point:
// Slum Snakes, CyberSec, Netburners, Fulcrum Secret Technologies,
// Silhouette
//Illuminati
var QLink = new Augmentation({
name:AugmentationNames.QLink, repCost:750e3, moneyCost:1300e6,
info:"A brain implant that wirelessly connects you to the Illuminati's " +
"quantum supercomputer, allowing you to access and use its incredible " +
"computing power.
" +
"This augmentation:
" +
"Increases the player's hacking speed by 10%
" +
"Increases the player's chance of successfully performing a hack by 30%
" +
"Increases the amount of money the player gains from hacking by 100%"
});
QLink.addToFactions(["Illuminati"]);
if (augmentationExists(AugmentationNames.QLink)) {
delete Augmentations[AugmentationNames.QLink];
}
AddToAugmentations(QLink);
//Daedalus
var RedPill = new Augmentation({
name:AugmentationNames.TheRedPill, repCost:1e6, moneyCost:0,
info:"It's time to leave the cave"
});
RedPill.addToFactions(["Daedalus"]);
if (augmentationExists(AugmentationNames.TheRedPill)) {
delete Augmentations[AugmentationNames.TheRedPill];
}
AddToAugmentations(RedPill);
//Covenant
var SPTN97 = new Augmentation({
name:AugmentationNames.SPTN97, repCost:500e3, moneyCost:975e6,
info:"The SPTN-97 gene is injected into the genome. The SPTN-97 gene is an " +
"artificially-synthesized gene that was developed by DARPA to create " +
"super-soldiers through genetic modification. The gene was outlawed in " +
"2056.
" +
"This augmentation:
" +
"Increases all of the player's combat stats by 75%
" +
"Increases the player's hacking skill by 15%"
});
SPTN97.addToFactions(["The Covenant"]);
if (augmentationExists(AugmentationNames.SPTN97)) {
delete Augmentations[AugmentationNames.SPTN97];
}
AddToAugmentations(SPTN97);
//ECorp
var HiveMind = new Augmentation({
name:AugmentationNames.HiveMind, repCost:600e3, moneyCost:1100e6,
info:"A brain implant developed by ECorp. They do not reveal what " +
"exactly the implant does, but they promise that it will greatly " +
"enhance your abilities."
});
HiveMind.addToFactions(["ECorp"]);
if (augmentationExists(AugmentationNames.HiveMind)) {
delete Augmentations[AugmentationNames.HiveMind];
}
AddToAugmentations(HiveMind);
//MegaCorp
var CordiARCReactor = new Augmentation({
name:AugmentationNames.CordiARCReactor, repCost:450e3, moneyCost:1000e6,
info:"The thoracic cavity is equipped with a small chamber designed " +
"to hold and sustain hydrogen plasma. The plasma is used to generate " +
"fusion power through nuclear fusion, providing limitless amount of clean " +
"energy for the body.
" +
"This augmentation:
" +
"Increases all of the player's combat stats by 35%
" +
"Increases all of the player's combat stat experience gain rate by 35%"
});
CordiARCReactor.addToFactions(["MegaCorp"]);
if (augmentationExists(AugmentationNames.CordiARCReactor)) {
delete Augmentations[AugmentationNames.CordiARCReactor];
}
AddToAugmentations(CordiARCReactor);
//BachmanAndAssociates
var SmartJaw = new Augmentation({
name:AugmentationNames.SmartJaw, repCost:150e3, moneyCost:550e6,
info:"A bionic jaw that contains advanced hardware and software " +
"capable of psychoanalyzing and profiling the personality of " +
"others using optical imaging software.
" +
"This augmentation:
" +
"Increases the player's charisma by 50%.
" +
"Increases the player's charisma experience gain rate by 50%
" +
"Increases the amount of reputation the player gains for a company by 25%
" +
"Increases the amount of reputation the player gains for a faction by 25%"
});
SmartJaw.addToFactions(["Bachman & Associates"]);
if (augmentationExists(AugmentationNames.SmartJaw)) {
delete Augmentations[AugmentationNames.SmartJaw];
}
AddToAugmentations(SmartJaw);
//BladeIndustries
var Neotra = new Augmentation({
name:AugmentationNames.Neotra, repCost:225e3, moneyCost:575e6,
info:"A highly-advanced techno-organic drug that is injected into the skeletal " +
"and integumentary system. The drug permanently modifies the DNA of the " +
"body's skin and bone cells, granting them the ability to repair " +
"and restructure themselves.
" +
"This augmentation increases the player's strength and defense by 55%"
});
Neotra.addToFactions(["Blade Industries"]);
if (augmentationExists(AugmentationNames.Neotra)) {
delete Augmentations[AugmentationNames.Neotra];
}
AddToAugmentations(Neotra);
//NWO
var Xanipher = new Augmentation({
name:AugmentationNames.Xanipher, repCost:350e3, moneyCost:850e6,
info:"A concoction of advanced nanobots that is orally ingested into the " +
"body. These nanobots induce physiological change and significantly " +
"improve the body's functionining in all aspects.
" +
"This augmentation:
" +
"Increases all of the player's stats by 20%
" +
"Increases the player's experience gain rate for all stats by 15%"
});
Xanipher.addToFactions(["NWO"]);
if (augmentationExists(AugmentationNames.Xanipher)) {
delete Augmentations[AugmentationNames.Xanipher];
}
AddToAugmentations(Xanipher);
//ClarkeIncorporated
var nextSENS = new Augmentation({
name:AugmentationNames.nextSENS, repCost:175e3, moneyCost:385e6,
info:"The body is genetically re-engineered to maintain a state " +
"of negligible senescence, preventing the body from " +
"deteriorating with age.
" +
"This augmentation increases all of the player's stats by 20%"
});
nextSENS.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.nextSENS)) {
delete Augmentations[AugmentationNames.nextSENS];
}
AddToAugmentations(nextSENS);
//OmniTekIncorporated
var OmniTekInfoLoad = new Augmentation({
name:AugmentationNames.OmniTekInfoLoad, repCost:250e3, moneyCost:575e6,
info:"OmniTek's data and information repository is uploaded " +
"into your brain, enhancing your programming and " +
"hacking abilities.
" +
"This augmentation:
" +
"Increases the player's hacking skill by 20%
" +
"Increases the player's hacking experience gain rate by 25%"
});
OmniTekInfoLoad.addToFactions(["OmniTek Incorporated"]);
if (augmentationExists(AugmentationNames.OmniTekInfoLoad)) {
delete Augmentations[AugmentationNames.OmniTekInfoLoad];
}
AddToAugmentations(OmniTekInfoLoad);
//FourSigma
//TODO Later when Intelligence is added in . Some aug that greatly increases int
//KuaiGongInternational
var PhotosyntheticCells = new Augmentation({
name:AugmentationNames.PhotosyntheticCells, repCost:225e3, moneyCost:550e6,
info:"Chloroplasts are added to epidermal stem cells and are applied " +
"to the body using a skin graft. The result is photosynthetic " +
"skin cells, allowing users to generate their own energy " +
"and nutrition using solar power.
" +
"This augmentation increases the player's strength, defense, and agility by 40%"
});
PhotosyntheticCells.addToFactions(["KuaiGong International"]);
if (augmentationExists(AugmentationNames.PhotosyntheticCells)) {
delete Augmentations[AugmentationNames.PhotosyntheticCells];
}
AddToAugmentations(PhotosyntheticCells);
//BitRunners
var Neurolink = new Augmentation({
name:AugmentationNames.Neurolink, repCost:350e3, moneyCost:875e6,
info:"A brain implant that provides a high-bandwidth, direct neural link between your " +
"mind and BitRunners' data servers, which reportedly contain " +
"the largest database of hacking tools and information in the world.
" +
"This augmentation:
" +
"Increases the player's hacking skill by 15%
" +
"Increases the player's hacking experience gain rate by 20%
" +
"Increases the player's chance of successfully performing a hack by 10%
" +
"Increases the player's hacking speed by 5%
" +
"Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset"
});
Neurolink.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.Neurolink)) {
delete Augmentations[AugmentationNames.Neurolink];
}
AddToAugmentations(Neurolink);
//BlackHand
var TheBlackHand = new Augmentation({
name:AugmentationNames.TheBlackHand, repCost:40e3, moneyCost:110e6,
info:"A highly advanced bionic hand. This prosthetic not only " +
"enhances strength and dexterity but it is also embedded " +
"with hardware and firmware that lets the user connect to, access and hack " +
"devices and machines just by touching them.
" +
"This augmentation:
" +
"Increases the player's strength and dexterity by 15%
" +
"Increases the player's hacking skill by 10%
" +
"Increases the player's hacking speed by 2%
" +
"Increases the amount of money the player gains from hacking by 10%"
});
TheBlackHand.addToFactions(["The Black Hand"]);
if (augmentationExists(AugmentationNames.TheBlackHand)) {
delete Augmentations[AugmentationNames.TheBlackHand];
}
AddToAugmentations(TheBlackHand);
//NiteSec
var CRTX42AA = new Augmentation({
name:AugmentationNames.CRTX42AA, repCost:18e3, moneyCost:45e6,
info:"The CRTX42-AA gene is injected into the genome. " +
"The CRTX42-AA is an artificially-synthesized gene that targets the visual and prefrontal " +
"cortex and improves cognitive abilities.
" +
"This augmentation:
" +
"Improves the player's hacking skill by 8%
" +
"Improves the player's hacking experience gain rate by 15%"
});
CRTX42AA.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.CRTX42AA)) {
delete Augmentations[AugmentationNames.CRTX42AA];
}
AddToAugmentations(CRTX42AA);
//Chongqing
var Neuregen = new Augmentation({
name:AugmentationNames.Neuregen, repCost:15e3, moneyCost:75e6,
info:"A drug that genetically modifies the neurons in the brain. " +
"The result is that these neurons never die and continuously " +
"regenerate and strengthen themselves.
" +
"This augmentation increases the player's hacking experience gain rate by 40%"
});
Neuregen.addToFactions(["Chongqing"]);
if (augmentationExists(AugmentationNames.Neuregen)) {
delete Augmentations[AugmentationNames.Neuregen];
}
AddToAugmentations(Neuregen);
//Sector12
var CashRoot = new Augmentation({
name:AugmentationNames.CashRoot, repCost:5e3, moneyCost:25e6,
info:"A collection of digital assets saved on a small chip. The chip is implanted " +
"into your wrist. A small jack in the chip allows you to connect it to a computer " +
"and upload the assets.
" +
"This augmentation:
" +
"Lets the player start with $1,000,000 after a reset
" +
"Lets the player start with the BruteSSH.exe program after a reset"
});
CashRoot.addToFactions(["Sector-12"]);
if (augmentationExists(AugmentationNames.CashRoot)) {
delete Augmentations[AugmentationNames.CashRoot];
}
AddToAugmentations(CashRoot);
//NewTokyo
var NutriGen = new Augmentation({
name:AugmentationNames.NutriGen, repCost:2500, moneyCost:500e3,
info:"A thermo-powered artificial nutrition generator. Endogenously " +
"synthesizes glucose, amino acids, and vitamins and redistributes them " +
"across the body. The device is powered by the body's naturally wasted " +
"energy in the form of heat.
" +
"This augmentation:
" +
"Increases the player's experience gain rate for all combat stats by 20%"
});
NutriGen.addToFactions(["New Tokyo"]);
if (augmentationExists(AugmentationNames.NutriGen)) {
delete Augmentations[AugmentationNames.NutriGen];
}
AddToAugmentations(NutriGen);
//Aevum
//TODO Later Something that lets you learn advanced math...this increases int
//and profits as a trader/from trading
//Ishima
var INFRARet = new Augmentation({
name:AugmentationNames.INFRARet, repCost:3e3, moneyCost:6e6,
info:"A retina implant consisting of a tiny chip that sits behind the " +
"retina. This implant lets people visually detect infrared radiation.
" +
"This augmentation:
" +
"Increases the player's crime success rate by 25%
" +
"Increases the amount of money the player gains from crimes by 10%
" +
"Increases the player's dexterity by 10%"
});
INFRARet.addToFactions(["Ishima"]);
if (augmentationExists(AugmentationNames.INFRARet)) {
delete Augmentations[AugmentationNames.INFRARet];
}
AddToAugmentations(INFRARet);
//Volhaven
var DermaForce = new Augmentation({
name:AugmentationNames.DermaForce, repCost:6e3, moneyCost:10e6,
info:"A synthetic skin is grafted onto the body. The skin consists of " +
"millions of nanobots capable of projecting high-density muon beams, " +
"creating an energy barrier around the user.
" +
"This augmentation increases the player's defense by 40%"
});
DermaForce.addToFactions(["Volhaven"]);
if (augmentationExists(AugmentationNames.DermaForce)) {
delete Augmentations[AugmentationNames.DermaForce];
}
AddToAugmentations(DermaForce);
//SpeakersForTheDead
var GrapheneBrachiBlades = new Augmentation({
name:AugmentationNames.GrapheneBrachiBlades, repCost:90e3, moneyCost:500e6,
info:"An upgrade to the BrachiBlades augmentation. It infuses " +
"the retractable blades with an advanced graphene material " +
"to make them much stronger and lighter.
" +
"This augmentation:
" +
"Increases the player's strength and defense by 40%
" +
"Increases the player's crime success rate by 10%
" +
"Increases the amount of money the player gains from crimes by 30%",
prereqs:[AugmentationNames.BrachiBlades],
});
GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(AugmentationNames.GrapheneBrachiBlades)) {
delete Augmentations[AugmentationNames.GrapheneBrachiBlades];
}
AddToAugmentations(GrapheneBrachiBlades);
//DarkArmy
var GrapheneBionicArms = new Augmentation({
name:AugmentationNames.GrapheneBionicArms, repCost:200e3, moneyCost:750e6,
info:"An upgrade to the Bionic Arms augmentation. It infuses the " +
"prosthetic arms with an advanced graphene material " +
"to make them much stronger and lighter.
" +
"This augmentation increases the player's strength and dexterity by 85%",
prereqs:[AugmentationNames.BionicArms],
});
GrapheneBionicArms.addToFactions(["The Dark Army"]);
if (augmentationExists(AugmentationNames.GrapheneBionicArms)) {
delete Augmentations[AugmentationNames.GrapheneBionicArms];
}
AddToAugmentations(GrapheneBionicArms);
//TheSyndicate
var BrachiBlades = new Augmentation({
name:AugmentationNames.BrachiBlades, repCost:5e3, moneyCost:18e6,
info:"A set of retractable plasteel blades are implanted in the arm, underneath the skin. " +
"
This augmentation:
" +
"Increases the player's strength and defense by 15%
" +
"Increases the player's crime success rate by 10%
" +
"Increases the amount of money the player gains from crimes by 15%"
});
BrachiBlades.addToFactions(["The Syndicate"]);
if (augmentationExists(AugmentationNames.BrachiBlades)) {
delete Augmentations[AugmentationNames.BrachiBlades];
}
AddToAugmentations(BrachiBlades);
//Tetrads
var BionicArms = new Augmentation({
name:AugmentationNames.BionicArms, repCost:25e3, moneyCost:55e6,
info:"Cybernetic arms created from plasteel and carbon fibers that completely replace " +
"the user's organic arms.
" +
"This augmentation increases the user's strength and dexterity by 30%"
});
BionicArms.addToFactions(["Tetrads"]);
if (augmentationExists(AugmentationNames.BionicArms)) {
delete Augmentations[AugmentationNames.BionicArms];
}
AddToAugmentations(BionicArms);
//TianDiHui
var SNA = new Augmentation({
name:AugmentationNames.SNA, repCost:2500, moneyCost:6e6,
info:"A cranial implant that affects the user's personality, making them better " +
"at negotiation in social situations.
" +
"This augmentation:
" +
"Increases the amount of money the player earns at a company by 10%
" +
"Increases the amount of reputation the player gains when working for a " +
"company or faction by 15%"
});
SNA.addToFactions(["Tian Di Hui"]);
if (augmentationExists(AugmentationNames.SNA)) {
delete Augmentations[AugmentationNames.SNA];
}
AddToAugmentations(SNA);
//For BitNode-2, add all Augmentations to crime/evil factions.
//Do this before adding special Augmentations that become available in later BitNodes
if (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN === 2) {
console.log("Adding all augmentations to crime factions for Bit node 2");
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Slum Snakes"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Tetrads"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Syndicate"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Dark Army"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["Speakers for the Dead"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["NiteSec"].addAllAugmentations();
_Faction_js__WEBPACK_IMPORTED_MODULE_3__["Factions"]["The Black Hand"].addAllAugmentations();
}
//Special Bladeburner Augmentations
var BladeburnersFactionName = "Bladeburners";
if (Object(_Faction_js__WEBPACK_IMPORTED_MODULE_3__["factionExists"])(BladeburnersFactionName)) {
var EsperEyewear = new Augmentation({
name:AugmentationNames.EsperEyewear, repCost:500, moneyCost:33e6,
info:"Ballistic-grade protective and retractable eyewear that was designed specially " +
"for Bladeburner units. This " +
"is implanted by installing a mechanical frame in the skull's orbit. " +
"This frame interfaces with the brain and allows the user to " +
"automatically extrude and extract the eyewear. The eyewear protects " +
"against debris, shrapnel, laser, flash, and gas. It is also " +
"embedded with a data processing chip that can be programmed to display an " +
"AR HUD and assist the user in field missions.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 3%
" +
"Increases the player's dexterity by 3%"
});
EsperEyewear.addToFactions([BladeburnersFactionName]);
resetAugmentation(EsperEyewear);
var EMS4Recombination = new Augmentation({
name:AugmentationNames.EMS4Recombination, repCost: 1e3, moneyCost:55e6,
info:"A DNA recombination of the EMS-4 Gene. This genetic engineering " +
"technique was originally used on Bladeburners during the Synthoid uprising " +
"to induce wakefulness and concentration, suppress fear, reduce empathy, and " +
"improve reflexes and memory-recall among other things.
" +
"This augmentation:
" +
"Increases the player's sucess chance in Bladeburner contracts/operations by 3%
" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 5%
" +
"Increases the player's Bladeburner stamina gain rate by 1%"
});
EMS4Recombination.addToFactions([BladeburnersFactionName]);
resetAugmentation(EMS4Recombination);
var OrionShoulder = new Augmentation({
name:AugmentationNames.OrionShoulder, repCost:2.5e3, moneyCost:110e6,
info:"A bionic shoulder augmentation for the right shoulder. Using cybernetics, " +
"the ORION-MKIV shoulder enhances the strength and dexterity " +
"of the user's right arm. It also provides protection due to its " +
"crystallized graphene plating.
" +
"This augmentation:
" +
"Increases the player's defense by 5%.
" +
"Increases the player's strength and dexterity by 3%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 4%"
});
OrionShoulder.addToFactions([BladeburnersFactionName]);
resetAugmentation(OrionShoulder);
var HyperionV1 = new Augmentation({
name:AugmentationNames.HyperionV1, repCost: 5e3, moneyCost:550e6,
info:"A pair of mini plasma cannons embedded into the hands. The Hyperion is capable " +
"of rapidly firing bolts of high-density plasma. The weapon is meant to " +
"be used against augmented enemies as the ionized " +
"nature of the plasma disrupts the electrical systems of Augmentations. However, " +
"it can also be effective against non-augmented enemies due to its high temperature " +
"and concussive force.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 5%"
});
HyperionV1.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV1);
var HyperionV2 = new Augmentation({
name:AugmentationNames.HyperionV2, repCost:10e3, moneyCost:1.1e9,
info:"A pair of mini plasma cannons embedded into the hands. This augmentation " +
"is more advanced and powerful than the original V1 model. This V2 model is " +
"more power-efficiency, more accurate, and can fire plasma bolts at a much " +
"higher velocity than the V1 model.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 7%",
prereqs:[AugmentationNames.HyperionV1]
});
HyperionV2.addToFactions([BladeburnersFactionName]);
resetAugmentation(HyperionV2);
var GolemSerum = new Augmentation({
name:AugmentationNames.GolemSerum, repCost:12.5e3, moneyCost:2.2e9,
info:"A serum that permanently enhances many aspects of a human's capabilities, " +
"including strength, speed, immune system performance, and mitochondrial efficiency. The " +
"serum was originally developed by the Chinese military in an attempt to " +
"create super soldiers.
" +
"This augmentation:
" +
"Increases all of the player's combat stats by 5%
" +
"Increases the player's Bladeburner stamina gain rate by 5%
"
});
GolemSerum.addToFactions([BladeburnersFactionName]);
resetAugmentation(GolemSerum);
var VangelisVirus = new Augmentation({
name:AugmentationNames.VangelisVirus, repCost:7.5e3, moneyCost:550e6,
info:"A synthetic symbiotic virus that is injected into the human brain tissue. The Vangelis virus " +
"heightens the senses and focus of its host, and also enhances its intuition.
" +
"This augmentation:
" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 10%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 4%
" +
"Increases the player's dexterity experience gain rate by 5%"
});
VangelisVirus.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus);
var VangelisVirus3 = new Augmentation({
name:AugmentationNames.VangelisVirus3, repCost:15e3, moneyCost:2.2e9,
info:"An improved version of Vangelis, a synthetic symbiotic virus that is " +
"injected into the human brain tissue. On top of the benefits of the original " +
"virus, this also grants an accelerated healing factor and enhanced " +
"agility/reflexes.
" +
"This augmentation:
" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%
" +
"Increases the player's defense and dexterity experience gain rate by 5%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 5%",
prereqs:[AugmentationNames.VangelisVirus]
});
VangelisVirus3.addToFactions([BladeburnersFactionName]);
resetAugmentation(VangelisVirus3);
var INTERLINKED = new Augmentation({
name:AugmentationNames.INTERLINKED, repCost:10e3, moneyCost:1.1e9,
info:"The DNA is genetically modified to enhance the human's body " +
"extracellular matrix (ECM). This improves the ECM's ability to " +
"structurally support the body and grants heightened strength and " +
"durability.
" +
"This augmentation:
" +
"Increases the player's experience gain rate for all combat stats by 4%
" +
"Increases the player's Bladeburner max stamina by 10%"
});
INTERLINKED.addToFactions([BladeburnersFactionName]);
resetAugmentation(INTERLINKED);
var BladeRunner = new Augmentation({
name:AugmentationNames.BladeRunner, repCost:8e3, moneyCost:1.65e9,
info:"A cybernetic foot augmentation that was specially created for Bladeburners " +
"during the Synthoid Uprising. The organic musculature of the human foot " +
"is enhanced with flexible carbon nanotube matrices that are controlled by " +
"intelligent servo-motors.
" +
"This augmentation:
" +
"Increases the player's agility by 5%
" +
"Increases the player's Bladeburner max stamina by 5%
" +
"Increases the player's Bladeburner stamina gain rate by 5%
"
});
BladeRunner.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeRunner);
var BladeArmor = new Augmentation({
name:AugmentationNames.BladeArmor, repCost:5e3, moneyCost:275e6,
info:"A powered exoskeleton suit (exosuit) designed as armor for Bladeburner units. This " +
"exoskeleton is incredibly adaptable and can protect the wearer from blunt, piercing, " +
"concussive, thermal, chemical, and electric trauma. It also enhances the user's " +
"strength and agility.
" +
"This augmentation:
" +
"Increases all of the player's combat stats by 2%
" +
"Increases the player's Bladeburner stamina gain rate by 2%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 3%",
});
BladeArmor.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmor);
var BladeArmorPowerCells = new Augmentation({
name:AugmentationNames.BladeArmorPowerCells, repCost:7.5e3, moneyCost:550e6,
info:"Upgrades the BLADE-51b Tesla Armor with Ion Power Cells, which are capable of " +
"more efficiently storing and using power.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 5%" +
"Increases the player's Bladeburner stamina gain rate by 2%
" +
"Increases the player's Bladeburner max stamina by 5%
",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorPowerCells.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorPowerCells);
var BladeArmorEnergyShielding = new Augmentation({
name:AugmentationNames.BladeArmorEnergyShielding, repCost:8.5e3, moneyCost:1.1e9,
info:"Upgrades the BLADE-51b Tesla Armor with a plasma energy propulsion system " +
"that is capable of projecting an energy shielding force field.
" +
"This augmentation:
" +
"Increases the player's defense by 5%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 6%",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorEnergyShielding.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorEnergyShielding);
var BladeArmorUnibeam = new Augmentation({
name:AugmentationNames.BladeArmorUnibeam, repCost:12.5e3, moneyCost:3.3e9,
info:"Upgrades the BLADE-51b Tesla Armor with a concentrated deuterium-fluoride laser " +
"weapon. It's precision an accuracy makes it useful for quickly neutralizing " +
"threats while keeping casualties to a minimum.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 8%",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorUnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorUnibeam);
var BladeArmorOmnibeam = new Augmentation({
name:AugmentationNames.BladeArmorOmnibeam, repCost:25e3, moneyCost:5.5e9,
info:"Upgrades the BLADE-51b Tesla Armor Unibeam augmentation to use " +
"multiple-fiber system. The upgraded weapon uses multiple fiber laser " +
"modules that combine together to form a single, more powerful beam of up to " +
"2000MW.
" +
"This augmentation:
" +
"Increases the player's success chance in Bladeburner contracts/operations by 10%",
prereqs:[AugmentationNames.BladeArmorUnibeam]
});
BladeArmorOmnibeam.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorOmnibeam);
var BladeArmorIPU = new Augmentation({
name:AugmentationNames.BladeArmorIPU, repCost: 6e3, moneyCost:220e6,
info:"Upgrades the BLADE-51b Tesla Armor with an AI Information Processing " +
"Unit that was specially designed to analyze Synthoid related data and " +
"information.
" +
"This augmentation:
" +
"Increases the player's effectiveness in Bladeburner Field Analysis by 15%
" +
"Increases the player's success chance in Bladeburner contracts/operations by 2%",
prereqs:[AugmentationNames.BladeArmor]
});
BladeArmorIPU.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladeArmorIPU);
var BladesSimulacrum = new Augmentation({
name:AugmentationNames.BladesSimulacrum, repCost:6e3, moneyCost:75e9,
info:"A highly-advanced matter phase-shifter module that is embedded " +
"in the brainstem and cerebellum. This augmentation allows " +
"the user to project and control a holographic simulacrum within an " +
"extremely large radius. These specially-modified holograms were specially " +
"weaponized by Bladeburner units to be used against Synthoids.
" +
"This augmentation allows you to perform Bladeburner actions and other " +
"actions (such as working, commiting crimes, etc.) at the same time."
});
BladesSimulacrum.addToFactions([BladeburnersFactionName]);
resetAugmentation(BladesSimulacrum);
}
//Update costs based on how many have been purchased
var mult = Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultipleAugMultiplier, _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length);
for (var name in Augmentations) {
if (Augmentations.hasOwnProperty(name)) {
Augmentations[name].baseCost *= mult;
}
}
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].reapplyAllAugmentations();
}
//Resets an Augmentation during (re-initizliation)
function resetAugmentation(newAugObject) {
if (!(newAugObject instanceof Augmentation)) {
throw new Error("Invalid argument 'newAugObject' passed into resetAugmentation");
}
var name = newAugObject.name;
if (augmentationExists(name)) {
delete Augmentations[name];
}
AddToAugmentations(newAugObject);
}
function applyAugmentation(aug, reapply=false) {
Augmentations[aug.name].owned = true;
switch(aug.name) {
//Combat stat augmentations
case AugmentationNames.Targeting1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.10;
break;
case AugmentationNames.Targeting2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.20;
break;
case AugmentationNames.Targeting3:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.30;
break;
case AugmentationNames.SyntheticHeart: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.5;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.5;
break;
case AugmentationNames.SynfibrilMuscle: //Medium-high level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.3;
break;
case AugmentationNames.CombatRib1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.1;
break;
case AugmentationNames.CombatRib2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.14;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.14;
break;
case AugmentationNames.CombatRib3:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.18;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.18;
break;
case AugmentationNames.NanofiberWeave: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2;
break;
case AugmentationNames.SubdermalArmor: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 2.2;
break;
case AugmentationNames.WiredReflexes: //Low level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05;
break;
case AugmentationNames.GrapheneBoneLacings: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.7;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.7;
break;
case AugmentationNames.BionicSpine: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.15;
break;
case AugmentationNames.GrapheneBionicSpine: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.6;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.6;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.6;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.6;
break;
case AugmentationNames.BionicLegs: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.6;
break;
case AugmentationNames.GrapheneBionicLegs: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 2.5;
break;
//Labor stats augmentations
case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.6;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.6;
break;
case AugmentationNames.TITN41Injection:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.SpeechProcessor: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2;
break;
//Hacking augmentations
case AugmentationNames.BitWire:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05;
break;
case AugmentationNames.ArtificialBioNeuralNetwork: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.12;
break;
case AugmentationNames.ArtificialSynapticPotentiation: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.05;
break;
case AugmentationNames.EnhancedMyelinSheathing: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08;
break;
case AugmentationNames.SynapticEnhancement: //Low Level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
break;
case AugmentationNames.NeuralRetentionEnhancement: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.DataJack: //Med low level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.25;
break;
case AugmentationNames.ENM: //Medium level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCore: //Medium level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.07;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.07;
break;
case AugmentationNames.ENMCoreV2: //Medium high level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCoreV3: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1;
break;
case AugmentationNames.ENMAnalyzeEngine: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.1;
break;
case AugmentationNames.ENMDMA: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.2;
break;
case AugmentationNames.Neuralstimulator: //Medium Level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.12;
break;
case AugmentationNames.NeuralAccelerator:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.2;
break;
case AugmentationNames.CranialSignalProcessorsG1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05;
break;
case AugmentationNames.CranialSignalProcessorsG2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.07;
break;
case AugmentationNames.CranialSignalProcessorsG3:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.09;
break;
case AugmentationNames.CranialSignalProcessorsG4:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.25;
break;
case AugmentationNames.CranialSignalProcessorsG5:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.25;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.75;
break;
case AugmentationNames.NeuronalDensification:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
break;
//Work augmentations
case AugmentationNames.NuoptimalInjectorImplant: //Low medium level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.2;
break;
case AugmentationNames.SpeechEnhancement: //Low level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.1;
break;
case AugmentationNames.FocusWire: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.2;
break;
case AugmentationNames.PCDNI: //Med level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08;
break;
case AugmentationNames.PCDNIOptimizer: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.75;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1;
break;
case AugmentationNames.PCDNINeuralNetwork: //High level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.ADRPheromone1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.1;
break;
case AugmentationNames.ADRPheromone2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.2;
break;
//Hacknet Node Augmentations
case AugmentationNames.HacknetNodeCPUUpload:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeCacheUpload:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.10;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeNICUpload:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.9;
break;
case AugmentationNames.HacknetNodeKernelDNI:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.25;
break;
case AugmentationNames.HacknetNodeCoreDNI:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.45;
break;
//Misc augmentations
case AugmentationNames.NeuroFluxGovernor:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_money_mult *= 1.01;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_purchase_cost_mult *= 0.99;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_ram_cost_mult *= 0.99;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_core_cost_mult *= 0.99;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacknet_node_level_cost_mult *= 0.99;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.01;
if (!reapply) {
Augmentations[aug.name].level = aug.level;
for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.length; ++i) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].level = aug.level;
break;
}
}
}
break;
case AugmentationNames.Neurotrainer1: //Low Level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.1;
break;
case AugmentationNames.Neurotrainer2: //Medium level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.Neurotrainer3: //High Level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.2;
break;
case AugmentationNames.Hypersight: //Medium high level
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.25;
break;
case AugmentationNames.HemoRecirculator:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.08;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.08;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.08;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.08;
break;
case AugmentationNames.SmartSonar:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.25;
break;
case AugmentationNames.PowerRecirculator:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.1;
break;
//Unique augmentations (for factions)
case AugmentationNames.QLink:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 2;
break;
case AugmentationNames.TheRedPill:
break;
case AugmentationNames.SPTN97:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.75;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.75;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.75;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.75;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15;
break;
case AugmentationNames.HiveMind:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_grow_mult *= 3;
break;
case AugmentationNames.CordiARCReactor:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.35;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.35;
break;
case AugmentationNames.SmartJaw:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.5;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.5;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.25;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.25;
break;
case AugmentationNames.Neotra:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.55;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.55;
break;
case AugmentationNames.Xanipher:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.nextSENS:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].charisma_mult *= 1.2;
break;
case AugmentationNames.OmniTekInfoLoad:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.PhotosyntheticCells:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.4;
break;
case AugmentationNames.Neurolink:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_chance_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.TheBlackHand:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_speed_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_money_mult *= 1.1;
break;
case AugmentationNames.CRTX42AA:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_mult *= 1.08;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.15;
break;
case AugmentationNames.Neuregen:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].hacking_exp_mult *= 1.4;
break;
case AugmentationNames.CashRoot:
break;
case AugmentationNames.NutriGen:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.2;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.2;
break;
case AugmentationNames.INFRARet:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.25;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.1;
break;
case AugmentationNames.DermaForce:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4;
break;
case AugmentationNames.GrapheneBrachiBlades:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.4;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.3;
break;
case AugmentationNames.GrapheneBionicArms:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.85;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.85;
break;
case AugmentationNames.BrachiBlades:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_success_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].crime_money_mult *= 1.15;
break;
case AugmentationNames.BionicArms:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.3;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.3;
break;
case AugmentationNames.SNA:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].work_money_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].company_rep_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].faction_rep_mult *= 1.15;
break;
//Bladeburner augmentations
case AugmentationNames.EsperEyewear:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.03;
break;
case AugmentationNames.EMS4Recombination:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.01;
break;
case AugmentationNames.OrionShoulder:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.03;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.04;
break;
case AugmentationNames.HyperionV1:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05;
break;
case AugmentationNames.HyperionV2:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.07;
break;
case AugmentationNames.GolemSerum:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.05;
break;
case AugmentationNames.VangelisVirus:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.1;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.04;
break;
case AugmentationNames.VangelisVirus3:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05;
break;
case AugmentationNames.INTERLINKED:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_exp_mult *= 1.04;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_exp_mult *= 1.04;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_exp_mult *= 1.04;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_exp_mult *= 1.04;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.1;
break;
case AugmentationNames.BladeRunner:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.05;
break;
case AugmentationNames.BladeArmor:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].strength_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].dexterity_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].agility_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.03;
break;
case AugmentationNames.BladeArmorPowerCells:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_stamina_gain_mult *= 1.02;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_max_stamina_mult *= 1.05;
break;
case AugmentationNames.BladeArmorEnergyShielding:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].defense_mult *= 1.05;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.06;
break;
case AugmentationNames.BladeArmorUnibeam:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.08;
break;
case AugmentationNames.BladeArmorOmnibeam:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.1;
break;
case AugmentationNames.BladeArmorIPU:
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_analysis_mult *= 1.15;
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bladeburner_success_chance_mult *= 1.02;
break;
case AugmentationNames.BladesSimulacrum: //No multiplier effect
break;
default:
throw new Error("ERROR: No such augmentation!");
return;
}
if (aug.name == AugmentationNames.NeuroFluxGovernor) {
for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.length; ++i) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
//Already have this aug, just upgrade the level
return;
}
}
}
if (!reapply) {
var ownedAug = new PlayerOwnedAugmentation(aug.name);
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.push(ownedAug);
}
}
function PlayerOwnedAugmentation(name) {
this.name = name;
this.level = 1;
}
function installAugmentations(cbScript=null) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length == 0) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You have not purchased any Augmentations to install!");
return false;
}
var augmentationList = "";
for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length; ++i) {
var aug = Augmentations[_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].name];
if (aug == null) {
console.log("ERROR. Invalid augmentation");
continue;
}
applyAugmentation(_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i]);
augmentationList += (aug.name + "
");
}
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations = [];
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_12__["dialogBoxCreate"])("You slowly drift to sleep as scientists put you under in order " +
"to install the following Augmentations:
" + augmentationList +
"
You wake up in your home...you feel different...");
Object(_Prestige_js__WEBPACK_IMPORTED_MODULE_7__["prestigeAugmentation"])();
//Run a script after prestiging
if (cbScript && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_15__["isString"])(cbScript)) {
var home = _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].getHomeComputer();
for (var i = 0; i < home.scripts.length; ++i) {
if (home.scripts[i].filename === cbScript) {
var script = home.scripts[i];
var ramUsage = script.ramUsage;
var ramAvailable = home.maxRam - home.ramUsed;
if (ramUsage > ramAvailable) {
return; //Not enough RAM
}
var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_9__["RunningScript"](script, []); //No args
runningScriptObj.threads = 1; //Only 1 thread
home.runningScripts.push(runningScriptObj);
Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_5__["addWorkerScript"])(runningScriptObj, home);
}
}
}
}
function augmentationExists(name) {
return Augmentations.hasOwnProperty(name);
}
//Used for testing balance
function giveAllAugmentations() {
for (var name in Augmentations) {
var aug = Augmentations[name];
if (aug == null) {continue;}
var ownedAug = new PlayerOwnedAugmentation(name);
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.push(ownedAug);
}
_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].reapplyAllAugmentations();
}
function displayAugmentationsContent() {
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent);
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h1", {
innerText:"Purchased Augmentations",
}));
//Bladeburner text, once mechanic is unlocked
var bladeburnerText = "\n";
if (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].bitNodeN === 6 || _NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_4__["hasBladeburnerSF"]) {
bladeburnerText = "Bladeburner Progress\n\n";
}
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("pre", {
width:"70%", whiteSpace:"pre-wrap", display:"block",
innerText:"Below is a list of all Augmentations you have purchased but not yet installed. Click the button below to install them.\n" +
"WARNING: Installing your Augmentations resets most of your progress, including:\n\n" +
"Stats/Skill levels and Experience\n" +
"Money\n" +
"Scripts on every computer but your home computer\n" +
"Purchased servers\n" +
"Hacknet Nodes\n" +
"Faction/Company reputation\n" +
"Stocks\n" +
bladeburnerText +
"Installing Augmentations lets you start over with the perks and benefits granted by all " +
"of the Augmentations you have ever installed. Also, you will keep any scripts and RAM/Core upgrades " +
"on your home computer (but you will lose all programs besides NUKE.exe)."
}));
//Install Augmentations button
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button", innerText:"Install Augmentations",
tooltip:"'I never asked for this'",
clickListener:()=>{
installAugmentations();
return false;
}
}));
//Backup button
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button flashing-button", innerText:"Backup Save (Export)",
tooltip:"It's always a good idea to backup/export your save!",
clickListener:()=>{
_SaveObject_js__WEBPACK_IMPORTED_MODULE_8__["saveObject"].exportGame();
return false;
}
}));
//Purchased/queued augmentations list
var queuedAugmentationsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("ul", {class:"augmentations-list"});
for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations.length; ++i) {
var augName = _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].name;
var aug = Augmentations[augName];
var displayName = augName;
if (augName === AugmentationNames.NeuroFluxGovernor) {
displayName += " - Level " + (_Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].queuedAugmentations[i].level);
}
var accordion = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
queuedAugmentationsList.appendChild(accordion[0]);
}
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(queuedAugmentationsList);
//Installed augmentations list
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("h1", {
innerText:"Installed Augmentations", marginTop:"8px",
}));
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("p", {
width:"70%", whiteSpace:"pre-wrap",
innerText:"List of all Augmentations (including Source Files) that have been " +
"installed. You have gained the effects of these Augmentations."
}));
var augmentationsList = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("ul", {class:"augmentations-list"});
//Expand/Collapse All buttons
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Expand All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (!allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Collapse All", display:"inline-block",
clickListener:()=>{
var allHeaders = augmentationsList.getElementsByClassName("accordion-header");
for (var i = 0; i < allHeaders.length; ++i) {
if (allHeaders[i].classList.contains("active")) {allHeaders[i].click();}
}
}
}));
//Sort Buttons
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort in Order",
tooltip:"Sorts the Augmentations alphabetically and Source Files in numerical order (1, 2, 3,...)",
clickListener:()=>{
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList);
//Create a copy of Player's Source Files and augs array and sort them
var sourceFiles = _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles.slice();
var augs = _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations.slice();
sourceFiles.sort((sf1, sf2)=>{
return sf1.n - sf2.n;
});
augs.sort((aug1, aug2)=>{
return aug1.name <= aug2.name ? -1 : 1;
});
displaySourceFiles(augmentationsList, sourceFiles);
displayAugmentations(augmentationsList, augs);
}
}));
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createElement"])("a", {
class:"a-link-button", fontSize:"14px", innerText:"Sort by Acquirement Time",
tooltip:"Sorts the Augmentations and Source Files based on when you acquired them (same as default)",
clickListener:()=>{
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["removeChildrenFromElement"])(augmentationsList);
displaySourceFiles(augmentationsList, _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles);
displayAugmentations(augmentationsList, _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations);
}
}));
//Source Files - Temporary...Will probably put in a separate pane Later
displaySourceFiles(augmentationsList, _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].sourceFiles);
displayAugmentations(augmentationsList, _Player_js__WEBPACK_IMPORTED_MODULE_6__["Player"].augmentations);
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].Display.augmentationsContent.appendChild(augmentationsList);
}
//Creates the accordion elements to display Augmentations
// @listElement - List DOM element to append accordion elements to
// @augs - Array of Augmentation objects
function displayAugmentations(listElement, augs) {
for (var i = 0; i < augs.length; ++i) {
var augName = augs[i].name;
var aug = Augmentations[augName];
var displayName = augName;
if (augName === AugmentationNames.NeuroFluxGovernor) {
displayName += " - Level " + (augs[i].level);
}
var accordion = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({hdrText:displayName, panelText:aug.info});
listElement.appendChild(accordion[0]);
}
}
//Creates the accordion elements to display Source Files
// @listElement - List DOM element to append accordion elements to
// @sourceFiles - Array of Source File objects
function displaySourceFiles(listElement, sourceFiles) {
for (var i = 0; i < sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + sourceFiles[i].n;
var sourceFileObject = _SourceFile_js__WEBPACK_IMPORTED_MODULE_11__["SourceFiles"][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + sourceFiles[i].n);
continue;
}
const maxLevel = sourceFiles[i].n == 12 ? "∞" : "3";
var accordion = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_13__["createAccordionElement"])({
hdrText:sourceFileObject.name + "
" + "Level " + (sourceFiles[i].lvl) + " / "+maxLevel,
panelText:sourceFileObject.info
});
listElement.appendChild(accordion[0]);
}
}
/***/ }),
/* 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/Settings.js ***!
\*************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return Settings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSettingsLabels", function() { return setSettingsLabels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadSettings", function() { return loadSettings; });
/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.js */ 5);
/* Settings.js */
let Settings = {
CodeInstructionRunTime: 50,
MaxLogCapacity: 50,
MaxPortCapacity: 50,
SuppressMessages: false,
SuppressFactionInvites: false,
SuppressTravelConfirmation: false,
SuppressBuyAugmentationConfirmation: false,
AutosaveInterval: 60,
DisableHotkeys: false,
ThemeHighlightColor: "#ffffff",
ThemeFontColor: "#66ff33",
ThemeBackgroundColor: "#000000",
EditorTheme: "Monokai",
EditorKeybinding: "ace",
}
function loadSettings(saveString) {
Settings = JSON.parse(saveString);
}
function initSettings() {
Settings.CodeInstructionRunTime = 50;
Settings.MaxLogCapacity = 50;
Settings.MaxPortCapacity = 50;
Settings.SuppressMessages = false;
Settings.SuppressFactionInvites = false;
Settings.SuppressTravelConfirmation = false,
Settings.SuppressBuyAugmentationConfirmation = false,
Settings.AutosaveInterval = 60;
Settings.DisableHotkeys = false;
}
function setSettingsLabels() {
var nsExecTime = document.getElementById("settingsNSExecTimeRangeValLabel");
var nsLogLimit = document.getElementById("settingsNSLogRangeValLabel");
var nsPortLimit = document.getElementById("settingsNSPortRangeValLabel");
var suppressMsgs = document.getElementById("settingsSuppressMessages");
var suppressFactionInv = document.getElementById("settingsSuppressFactionInvites")
var suppressTravelConfirmation = document.getElementById("settingsSuppressTravelConfirmation");
var suppressBuyAugmentationConfirmation = document.getElementById("settingsSuppressBuyAugmentationConfirmation");
var autosaveInterval = document.getElementById("settingsAutosaveIntervalValLabel");
var disableHotkeys = document.getElementById("settingsDisableHotkeys");
//Initialize values on labels
nsExecTime.innerHTML = Settings.CodeInstructionRunTime + "ms";
nsLogLimit.innerHTML = Settings.MaxLogCapacity;
nsPortLimit.innerHTML = Settings.MaxPortCapacity;
suppressMsgs.checked = Settings.SuppressMessages;
suppressFactionInv.checked = Settings.SuppressFactionInvites;
suppressTravelConfirmation.checked = Settings.SuppressTravelConfirmation;
suppressBuyAugmentationConfirmation.checked = Settings.SuppressBuyAugmentationConfirmation;
autosaveInterval.innerHTML = Settings.AutosaveInterval;
disableHotkeys.checked = Settings.DisableHotkeys;
//Set handlers for when input changes
var nsExecTimeInput = document.getElementById("settingsNSExecTimeRangeVal");
var nsLogRangeInput = document.getElementById("settingsNSLogRangeVal");
var nsPortRangeInput = document.getElementById("settingsNSPortRangeVal");
var nsAutosaveIntervalInput = document.getElementById("settingsAutosaveIntervalVal");
nsExecTimeInput.value = Settings.CodeInstructionRunTime;
nsLogRangeInput.value = Settings.MaxLogCapacity;
nsPortRangeInput.value = Settings.MaxPortCapacity;
nsAutosaveIntervalInput.value = Settings.AutosaveInterval;
nsExecTimeInput.oninput = function() {
nsExecTime.innerHTML = this.value + 'ms';
Settings.CodeInstructionRunTime = this.value;
};
nsLogRangeInput.oninput = function() {
nsLogLimit.innerHTML = this.value;
Settings.MaxLogCapacity = this.value;
};
nsPortRangeInput.oninput = function() {
nsPortLimit.innerHTML = this.value;
Settings.MaxPortCapacity = this.value;
};
nsAutosaveIntervalInput.oninput = function() {
autosaveInterval.innerHTML = this.value;
Settings.AutosaveInterval = Number(this.value);
if (Number(this.value) === 0) {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Infinity;
} else {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = Number(this.value) * 5;
}
};
suppressMsgs.onclick = function() {
Settings.SuppressMessages = this.checked;
};
suppressFactionInv.onclick = function() {
Settings.SuppressFactionInvites = this.checked;
};
suppressTravelConfirmation.onclick = function() {
Settings.SuppressTravelConfirmation = this.checked;
};
suppressBuyAugmentationConfirmation.onclick = function() {
Settings.SuppressBuyAugmentationConfirmation = this.checked;
console.log('sup buy: '+Settings.SuppressBuyAugmentationConfirmation);
};
disableHotkeys.onclick = function() {
Settings.DisableHotkeys = this.checked;
}
//Theme
if (Settings.ThemeHighlightColor == null || Settings.ThemeFontColor == null || Settings.ThemeBackgroundColor == null) {
console.log("ERROR: Cannot find Theme Settings");
return;
}
if (/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeHighlightColor) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeFontColor) &&
/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(Settings.ThemeBackgroundColor)) {
document.body.style.setProperty('--my-highlight-color', Settings.ThemeHighlightColor);
document.body.style.setProperty('--my-font-color', Settings.ThemeFontColor);
document.body.style.setProperty('--my-background-color', Settings.ThemeBackgroundColor);
}
}
/***/ }),
/* 18 */
/*!*************************!*\
!*** ./src/Terminal.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__, "postNetburnerText", function() { return postNetburnerText; });
/* 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 */ 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 */ 20);
/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./DarkWeb.js */ 59);
/* 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 */ 30);
/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./HelpText */ 67);
/* harmony import */ var _HelpText__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_HelpText__WEBPACK_IMPORTED_MODULE_6__);
/* 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 numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! numeral/min/numeral.min */ 10);
/* harmony import */ var numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(numeral_min_numeral_min__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Player.js */ 0);
/* harmony import */ var _RedPill_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./RedPill.js */ 34);
/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Script.js */ 24);
/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Server.js */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Settings.js */ 17);
/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./TextFile */ 58);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_19__);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__);
/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
/* harmony import */ var _utils_LogBox_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../utils/LogBox.js */ 47);
/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! jszip */ 122);
/* harmony import */ var jszip__WEBPACK_IMPORTED_MODULE_24___default = /*#__PURE__*/__webpack_require__.n(jszip__WEBPACK_IMPORTED_MODULE_24__);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! file-saver */ 121);
/* harmony import */ var file_saver__WEBPACK_IMPORTED_MODULE_25___default = /*#__PURE__*/__webpack_require__.n(file_saver__WEBPACK_IMPORTED_MODULE_25__);
/* Write text to terminal */
//If replace is true then spaces are replaced with " "
function post(input) {
$("#terminal-input").before(' ');
updateTerminalScroll();
}
//Same thing as post but the td cells have ids so they can be animated for the hack progress bar
function hackProgressBarPost(input) {
$("#terminal-input").before('' + input + ' ');
updateTerminalScroll();
}
function hackProgressPost(input) {
$("#terminal-input").before('' + input + ' ');
updateTerminalScroll();
}
//Scroll to the bottom of the terminal's 'text area'
function updateTerminalScroll() {
var element = document.getElementById("terminal-container");
element.scrollTop = element.scrollHeight;
}
function postNetburnerText() {
post("Bitburner v" + _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].Version);
}
//Key Codes
var KEY = {
TAB: 9,
ENTER: 13,
CTRL: 17,
UPARROW: 38,
DOWNARROW: 40,
A: 65,
B: 66,
C: 67,
D: 68,
E: 69,
F: 70,
H: 72,
J: 74,
K: 75,
L: 76,
M: 77,
N: 78,
O: 79,
P: 80,
R: 82,
S: 83,
U: 85,
W: 87,
}
//Defines key commands in terminal
$(document).keydown(function(event) {
//Terminal
if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput != null && !event.ctrlKey && !event.shiftKey) {terminalInput.focus();}
if (event.keyCode === KEY.ENTER) {
event.preventDefault(); //Prevent newline from being entered in Script Editor
var command = $('input[class=terminal-input]').val();
if (command.length > 0) {
post(
"[" +
(_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_TIMESTAMPS ? Terminal.getTimestamp() + " " : "") +
_Player_js__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer().hostname +
" ~]> " + command
);
Terminal.resetTerminalInput(); //Clear input first
Terminal.executeCommand(command);
}
}
if (event.keyCode === KEY.C && event.ctrlKey) {
if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress) {
//Cancel action
post("Cancelling...");
_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"]._actionInProgress = false;
Terminal.finishAction(true);
} else if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
//Dont prevent default so it still copies
Terminal.resetTerminalInput(); //Clear Terminal
}
}
if (event.keyCode === KEY.L && event.ctrlKey) {
event.preventDefault();
Terminal.executeCommand("clear"); //Clear screen
}
//Ctrl p same as up arrow
//Ctrl n same as down arrow
if (event.keyCode === KEY.UPARROW ||
(_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.P && event.ctrlKey)) {
if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
//Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {return;}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
}
if (i != 0) {
--Terminal.commandHistoryIndex;
}
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
setTimeout(function(){terminalInput.selectionStart = terminalInput.selectionEnd = 10000; }, 0);
}
if (event.keyCode === KEY.DOWNARROW ||
(_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS && event.keyCode === KEY.M && event.ctrlKey)) {
if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {event.preventDefault();}
//Cycle through past commands
if (terminalInput == null) {return;}
var i = Terminal.commandHistoryIndex;
var len = Terminal.commandHistory.length;
if (len == 0) {return;}
if (i < 0 || i > len) {
Terminal.commandHistoryIndex = len;
}
//Latest command, put nothing
if (i == len || i == len-1) {
Terminal.commandHistoryIndex = len;
terminalInput.value = "";
} else {
++Terminal.commandHistoryIndex;
var prevCommand = Terminal.commandHistory[Terminal.commandHistoryIndex];
terminalInput.value = prevCommand;
}
}
if (event.keyCode === KEY.TAB) {
//Autocomplete
if (terminalInput == null) {return;}
var input = terminalInput.value;
if (input == "") {return;}
input = input.trim();
input = input.replace(/\s\s+/g, ' ');
var commandArray = input.split(" ");
var index = commandArray.length - 2;
if (index < -1) {index = 0;}
var allPos = determineAllPossibilitiesForTabCompletion(input, index);
if (allPos.length == 0) {return;}
var arg = "";
var command = "";
if (commandArray.length == 0) {return;}
if (commandArray.length == 1) {command = commandArray[0];}
else if (commandArray.length == 2) {
command = commandArray[0];
arg = commandArray[1];
} else if (commandArray.length == 3) {
command = commandArray[0] + " " + commandArray[1];
arg = commandArray[2];
} else {
arg = commandArray.pop();
command = commandArray.join(" ");
}
tabCompletion(command, arg, allPos);
}
//Extra Bash Emulation Hotkeys, must be enabled through .fconf
if (_Fconf_js__WEBPACK_IMPORTED_MODULE_5__["FconfSettings"].ENABLE_BASH_HOTKEYS) {
if (event.keyCode === KEY.A && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("home");
}
if (event.keyCode === KEY.E && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("end");
}
if (event.keyCode === KEY.B && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("prevchar");
}
if (event.keyCode === KEY.B && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("prevword");
}
if (event.keyCode === KEY.F && event.ctrlKey) {
event.preventDefault();
Terminal.moveTextCursor("nextchar");
}
if (event.keyCode === KEY.F && event.altKey) {
event.preventDefault();
Terminal.moveTextCursor("nextword");
}
if ((event.keyCode === KEY.H || event.keyCode === KEY.D) && event.ctrlKey) {
Terminal.modifyInput("backspace");
event.preventDefault();
}
//TODO AFTER THIS:
//alt + d deletes word after cursor
//^w deletes word before cursor
//^k clears line after cursor
//^u clears line before cursor
}
}
});
//Keep terminal in focus
let terminalCtrlPressed = false, shiftKeyPressed = false;
$(document).ready(function() {
if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage === _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
$('.terminal-input').focus();
}
});
$(document).keydown(function(e) {
if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
if (e.which == 17) {
terminalCtrlPressed = true;
} else if (e.shiftKey) {
shiftKeyPressed = true;
} else if (terminalCtrlPressed || shiftKeyPressed) {
//Don't focus
} else {
var inputTextBox = document.getElementById("terminal-input-text-box");
if (inputTextBox != null) {inputTextBox.focus();}
terminalCtrlPressed = false;
shiftKeyPressed = false;
}
}
})
$(document).keyup(function(e) {
if (_engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_4__["Engine"].Page.Terminal) {
if (e.which == 17) {
terminalCtrlPressed = false;
}
if (e.shiftKey) {
shiftKeyPressed = false;
}
}
})
//Implements a tab completion feature for terminal
// command - Command (first arg only)
// arg - Incomplete argument string that the function will try to complete, or will display
// a series of possible options for
// allPossibilities - Array of strings containing all possibilities that the
// string can complete to
// index - index of argument that is being "tab completed". By default is 0, the first argument
function tabCompletion(command, arg, allPossibilities, index=0) {
if (!(allPossibilities.constructor === Array)) {return;}
if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["containsAllStrings"])(allPossibilities)) {return;}
if (!command.startsWith("./")) {
command = command.toLowerCase();
}
//Remove all options in allPossibilities that do not match the current string
//that we are attempting to autocomplete
if (arg == "") {
for (var i = allPossibilities.length-1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(command.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
} else {
for (var i = allPossibilities.length-1; i >= 0; --i) {
if (!allPossibilities[i].toLowerCase().startsWith(arg.toLowerCase())) {
allPossibilities.splice(i, 1);
}
}
}
var val = "";
if (allPossibilities.length == 0) {
return;
} else if (allPossibilities.length == 1) {
if (arg == "") {
//Autocomplete command
val = allPossibilities[0] + " ";
} else {
val = command + " " + allPossibilities[0];
}
document.getElementById("terminal-input-text-box").value = val;
document.getElementById("terminal-input-text-box").focus();
} else {
var longestStartSubstr = Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["longestCommonStart"])(allPossibilities);
//If the longest common starting substring of remaining possibilities is the same
//as whatevers already in terminal, just list all possible options. Otherwise,
//change the input in the terminal to the longest common starting substr
var allOptionsStr = "";
for (var i = 0; i < allPossibilities.length; ++i) {
allOptionsStr += allPossibilities[i];
allOptionsStr += " ";
}
if (arg == "") {
if (longestStartSubstr == command) {
post("> " + command);
post(allOptionsStr);
} else {
document.getElementById("terminal-input-text-box").value = longestStartSubstr;
document.getElementById("terminal-input-text-box").focus();
}
} else {
if (longestStartSubstr == arg) {
//List all possible options
post("> " + command + " " + arg);
post(allOptionsStr);
} else {
document.getElementById("terminal-input-text-box").value = command + " " + longestStartSubstr;
document.getElementById("terminal-input-text-box").focus();
}
}
}
}
function determineAllPossibilitiesForTabCompletion(input, index=0) {
var allPos = [];
allPos = allPos.concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
var currServ = _Player_js__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer();
input = input.toLowerCase();
//If the command starts with './' and the index == -1, then the user
//has input ./partialexecutablename so autocomplete the script or program
//Put './' in front of each script/executable
if (input.startsWith("./") && index == -1) {
//All programs and scripts
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push("./" + currServ.scripts[i].filename);
}
//Programs are on home computer
var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_13__["Player"].getHomeComputer();
for(var i = 0; i < homeComputer.programs.length; ++i) {
allPos.push("./" + homeComputer.programs[i]);
}
return allPos;
}
//Autocomplete the command
if (index == -1) {
return ["alias", "analyze", "cat", "check", "clear", "cls", "connect", "download", "free",
"hack", "help", "home", "hostname", "ifconfig", "kill", "killall",
"ls", "lscpu", "mem", "nano", "ps", "rm", "run", "scan", "scan-analyze",
"scp", "sudov", "tail", "theme", "top"].concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["Aliases"])).concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
}
if (input.startsWith ("buy ")) {
let options = [];
for(const i in _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__["DarkWebItems"]) {
const item = _DarkWeb_js__WEBPACK_IMPORTED_MODULE_3__["DarkWebItems"][i]
options.push(item.program);
}
return options.concat(Object.keys(_Alias_js__WEBPACK_IMPORTED_MODULE_0__["GlobalAliases"]));
}
if (input.startsWith("scp ") && index == 1) {
for (var iphostname in _Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"]) {
if (_Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"].hasOwnProperty(iphostname)) {
allPos.push(_Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"][iphostname].ip);
allPos.push(_Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"][iphostname].hostname);
}
}
}
if (input.startsWith("scp ") && index == 0) {
//All Scripts and lit files
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"])) {
allPos.push(currServ.messages[i]);
}
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
}
if (input.startsWith("connect ") || input.startsWith("telnet ")) {
//All network connections
for (var i = 0; i < currServ.serversOnNetwork.length; ++i) {
var serv = _Server_js__WEBPACK_IMPORTED_MODULE_16__["AllServers"][currServ.serversOnNetwork[i]];
if (serv == null) {continue;}
allPos.push(serv.ip); //IP
allPos.push(serv.hostname); //Hostname
}
return allPos;
}
if (input.startsWith("kill ") || input.startsWith("tail ") ||
input.startsWith("mem ") || input.startsWith("check ")) {
//All Scripts
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
return allPos;
}
if (input.startsWith("nano ")) {
//Scripts and text files and .fconf
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
allPos.push(".fconf");
return allPos;
}
if (input.startsWith("rm ")) {
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
for (var i = 0; i < currServ.programs.length; ++i) {
allPos.push(currServ.programs[i]);
}
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"]) && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_20__["isString"])(currServ.messages[i]) &&
currServ.messages[i].endsWith(".lit")) {
allPos.push(currServ.messages[i]);
}
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
return allPos;
}
if (input.startsWith("run ")) {
//All programs and scripts
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
//Programs are on home computer
var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_13__["Player"].getHomeComputer();
for(var i = 0; i < homeComputer.programs.length; ++i) {
allPos.push(homeComputer.programs[i]);
}
return allPos;
}
if (input.startsWith("cat ")) {
for (var i = 0; i < currServ.messages.length; ++i) {
if (currServ.messages[i] instanceof _Message_js__WEBPACK_IMPORTED_MODULE_9__["Message"]) {
allPos.push(currServ.messages[i].filename);
} else {
allPos.push(currServ.messages[i]);
}
}
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
return allPos;
}
if (input.startsWith("download ")) {
for (var i = 0; i < currServ.textFiles.length; ++i) {
allPos.push(currServ.textFiles[i].fn);
}
for (var i = 0; i < currServ.scripts.length; ++i) {
allPos.push(currServ.scripts[i].filename);
}
}
return allPos;
}
let Terminal = {
//Flags to determine whether the player is currently running a hack or an analyze
hackFlag: false,
analyzeFlag: false,
commandHistory: [],
commandHistoryIndex: 0,
resetTerminalInput: function() {
document.getElementById("terminal-input-td").innerHTML =
"' + input + '
" +
"Do you want to travel to the BitNode Nexus? This allows you to reset the current BitNode " +
"and select a new one.");
break;
default:
post("Invalid executable. Cannot be run");
return;
}
},
runScript: function(scriptName) {
var server = _Player_js__WEBPACK_IMPORTED_MODULE_13__["Player"].getCurrentServer();
var numThreads = 1;
var args = [];
var results = scriptName.split(" ");
if (results.length <= 0) {
post("This is a bug. Please contact developer");
}
scriptName = results[0];
if (results.length > 1) {
if (results.length >= 3 && results[1] == "-t") {
numThreads = Math.round(Number(results[2]));
if (isNaN(numThreads) || numThreads < 1) {
post("Invalid number of threads specified. Number of threads must be greater than 0");
return;
}
for (var i = 3; i < results.length; ++i) {
var arg = results[i];
//Forced string
if ((arg.startsWith("'") && arg.endsWith("'")) ||
(arg.startsWith('"') && arg.endsWith('"'))) {
args.push(arg.slice(1, -1));
continue;
}
//Number
var tempNum = Number(arg);
if (!isNaN(tempNum)) {
args.push(tempNum);
continue;
}
//Otherwise string
args.push(arg);
}
} else {
for (var i = 1; i < results.length; ++i) {
var arg = results[i];
//Forced string
if ((arg.startsWith("'") && arg.endsWith("'")) ||
(arg.startsWith('"') && arg.endsWith('"'))) {
args.push(arg.slice(1, -1));
continue;
}
//Number
var tempNum = Number(arg);
if (!isNaN(tempNum)) {
args.push(tempNum);
continue;
}
//Otherwise string
args.push(arg);
}
}
}
//Check if this script is already running
if (Object(_Script_js__WEBPACK_IMPORTED_MODULE_15__["findRunningScript"])(scriptName, args, server) != null) {
post("ERROR: This script is already running. Cannot run multiple instances");
return;
}
//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 * numThreads * Math.pow(_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].MultithreadingRAMCost, numThreads-1);
var ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
post("Need root access to run script");
return;
} else if (ramUsage > ramAvailable){
post("This machine does not have enough RAM to run this script with " +
numThreads + " threads. Script requires " + ramUsage + "GB of RAM");
return;
} else {
//Able to run script
post("Running script with " + numThreads + " thread(s) and args: " + Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_21__["printArray"])(args) + ".");
post("May take a few seconds to start up the process...");
var runningScriptObj = new _Script_js__WEBPACK_IMPORTED_MODULE_15__["RunningScript"](script, args);
runningScriptObj.threads = numThreads;
server.runningScripts.push(runningScriptObj);
Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_11__["addWorkerScript"])(runningScriptObj, server);
return;
}
}
}
post("ERROR: No such script");
}
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 37)))
/***/ }),
/* 19 */
/*!************************************************!*\
!*** ./node_modules/decimal.js/decimal.es6.js ***!
\************************************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
*
* decimal.js v7.2.3
* An arbitrary-precision Decimal type for JavaScript.
* https://github.com/MikeMcl/decimal.js
* Copyright (c) 2017 Michael Mclaughlin
" +
"This tutorial will show you the basics of the game. " +
"You may skip the tutorial at any time.");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.GoToCharacterPage:
iTutorialSetText("Let's start by heading to the Stats page. Click the 'Stats' tab on " +
"the main navigation menu (left-hand side of the screen)");
//No next button
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "none";
//Flash Character tab
document.getElementById("stats-menu-link").setAttribute("class", "flashing-button");
//Initialize everything necessary to open the "Character" page
var charaterMainMenuButton = document.getElementById("stats-menu-link");
charaterMainMenuButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadCharacterContent();
iTutorialNextStep(); //Opening the character page will go to the next step
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("stats-menu-link");
return false;
});
break;
case iTutorialSteps.CharacterPage:
iTutorialSetText("The Stats page shows a lot of important information about your progress, " +
"such as your skills, money, and bonuses/multipliers. ")
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.CharacterGoToTerminalPage:
iTutorialSetText("Let's head to your computer's terminal by clicking the 'Terminal' tab on the " +
"main navigation menu.");
//No next button
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "none";
document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button");
//Initialize everything necessary to open the 'Terminal' Page
var terminalMainMenuButton = document.getElementById("terminal-menu-link");
terminalMainMenuButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
return false;
});
break;
case iTutorialSteps.TerminalIntro:
iTutorialSetText("The Terminal is used to interface with your home computer as well as " +
"all of the other machines around the world.");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TerminalHelp:
iTutorialSetText("Let's try it out. Start by entering the 'help' command into the Terminal " +
"(Don't forget to press Enter after typing the command)");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "none";
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalLs:
iTutorialSetText("The 'help' command displays a list of all available Terminal commands, how to use them, " +
"and a description of what they do.
Let's try another command. Enter the 'ls' command");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalScan:
iTutorialSetText("'ls' is a basic command that shows all of the contents (programs/scripts) " +
"on the computer. Right now, it shows that you have a program called 'NUKE.exe' on your computer. " +
"We'll get to what this does later.
Using your home computer's terminal, you can connect " +
"to other machines throughout the world. Let's do that now by first entering " +
"the 'scan' command. ");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze1:
iTutorialSetText("The 'scan' command shows all available network connections. In other words, " +
"it displays a list of all servers that can be connected to from your " +
"current machine. A server is identified by either its IP or its hostname.
" +
"That's great and all, but there's so many servers. Which one should you go to? " +
"The 'scan-analyze' command gives some more detailed information about servers on the " +
"network. Try it now");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalScanAnalyze2:
iTutorialSetText("You just ran 'scan-analyze' with a depth of one. This command shows more detailed " +
"information about each server that you can connect to (servers that are a distance of " +
"one node away).
It is also possible to run 'scan-analyze' with " +
"a higher depth. Let's try a depth of two with the following command: 'scan-analyze 2'.")
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalConnect:
iTutorialSetText("Now you can see information about all servers that are up to two nodes away, as well " +
"as figure out how to navigate to those servers through the network. You can only connect to " +
"a server that is one node away. To connect to a machine, use the 'connect [ip/hostname]' command. You can type in " +
"the ip or the hostname, but dont use both.
" +
"From the results of the 'scan-analyze' command, we can see that the 'foodnstuff' server is " +
"only one node away. Let's connect so it now using: 'connect foodnstuff'");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalAnalyze:
iTutorialSetText("You are now connected to another machine! What can you do now? You can hack it!
In the year 2077, currency has " +
"become digital and decentralized. People and corporations store their money " +
"on servers and computers. Using your hacking abilities, you can hack servers " +
"to steal money and gain experience.
" +
"Before you try to hack a server, you should run diagnostics using the 'analyze' command");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalNuke:
iTutorialSetText("When the 'analyze' command finishes running it will show useful information " +
"about hacking the server.
For this server, the required hacking skill is only 1, " +
"which means you can hack it right now. However, in order to hack a server " +
"you must first gain root access. The 'NUKE.exe' program that we saw earlier on your " +
"home computer is a virus that will grant you root access to a machine if there are enough " +
"open ports.
The 'analyze' results shows that there do not need to be any open ports " +
"on this machine for the NUKE virus to work, so go ahead and run the virus using the " +
"'run NUKE.exe' command.");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalManualHack:
iTutorialSetText("You now have root access! You can hack the server using the 'hack' command. " +
"Try doing that now.");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalHackingMechanics:
iTutorialSetText("You are now attempting to hack the server. Note that performing a hack takes time and " +
"only has a certain percentage chance " +
"of success. This time and success chance is determined by a variety of factors, including " +
"your hacking skill and the server's security level.
" +
"If your attempt to hack the server is successful, you will steal a certain percentage " +
"of the server's total money. This percentage is affected by your hacking skill and " +
"the server's security level.
The amount of money on a server is not limitless. So, if " +
"you constantly hack a server and deplete its money, then you will encounter " +
"diminishing returns in your hacking.");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.TerminalCreateScript:
iTutorialSetText("Hacking is the core mechanic of the game and is necessary for progressing. However, " +
"you don't want to be hacking manually the entire time. You can automate your hacking " +
"by writing scripts!
To create a new script or edit an existing one, you can use the 'nano' " +
"command. Scripts must end with the '.script' extension. Let's make a script now by " +
"entering 'nano foodnstuff.script' after the hack command finishes running (Sidenote: Pressing ctrl + c" +
" will end a command like hack early)");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "none";
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalTypeScript:
iTutorialSetText("This is the script editor. You can use it to program your scripts. Scripts are " +
"written in the Netscript language, a programming language created for " +
"this game. There are details about the Netscript language in the documentation, which " +
"can be accessed in the 'Tutorial' tab on the main navigation menu. I highly suggest you check " +
"it out after this tutorial. For now, just copy " +
"and paste the following code into the script editor:
" +
"while(true) {
" +
" hack('foodnstuff');
" +
"}
" +
"For anyone with basic programming experience, this code should be straightforward. " +
"This script will continuously hack the 'foodnstuff' server.
" +
"To save and close the script editor, press the button in the bottom left, or press ctrl + b.");
//next step triggered in saveAndCloseScriptEditor() (Script.js)
break;
case iTutorialSteps.TerminalFree:
iTutorialSetText("Now we'll run the script. Scripts require a certain amount of RAM to run, and can be " +
"run on any machine which you have root access to. Different servers have different " +
"amounts of RAM. You can also purchase more RAM for your home server.
To check how much " +
"RAM is available on this machine, enter the 'free' command.");
//next step triggered by terminal commmand
break;
case iTutorialSteps.TerminalRunScript:
iTutorialSetText("We have 16GB of free RAM on this machine, which is enough to run our " +
"script. Let's run our script using 'run foodnstuff.script'.");
//next step triggered by terminal commmand
break;
case iTutorialSteps.TerminalGoToActiveScriptsPage:
iTutorialSetText("Your script is now running! The script might take a few seconds to 'fully start up'. " +
"Your scripts will continuously run in the background and will automatically stop if " +
"the code ever completes (the 'foodnstuff.script' will never complete because it " +
"runs an infinite loop).
These scripts can passively earn you income and hacking experience. " +
"Your scripts will also earn money and experience while you are offline, although at a " +
"much slower rate.
" +
"Let's check out some statistics for our running scripts by clicking the " +
"'Active Scripts' link in the main navigation menu.");
document.getElementById("active-scripts-menu-link").setAttribute("class", "flashing-button");
var activeScriptsMainMenuButton = document.getElementById("active-scripts-menu-link");
activeScriptsMainMenuButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadActiveScriptsContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("active-scripts-menu-link");
return false;
});
break;
case iTutorialSteps.ActiveScriptsPage:
iTutorialSetText("This page displays stats/information about all of your scripts that are " +
"running across every existing server. You can use this to gauge how well " +
"your scripts are doing. Let's go back to the Terminal now using the 'Terminal'" +
"link.");
document.getElementById("terminal-menu-link").setAttribute("class", "flashing-button");
//Initialize everything necessary to open the 'Terminal' Page
var terminalMainMenuButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
terminalMainMenuButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTerminalContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("terminal-menu-link");
return false;
});
break;
case iTutorialSteps.ActiveScriptsToTerminal:
iTutorialSetText("One last thing about scripts, each active script contains logs that detail " +
"what it's doing. We can check these logs using the 'tail' command. Do that " +
"now for the script we just ran by typing 'tail foodnstuff.script'");
//next step triggered by terminal command
break;
case iTutorialSteps.TerminalTailScript:
iTutorialSetText("The log for this script won't show much right now (it might show nothing at all) because it " +
"just started running...but check back again in a few minutes!
" +
"This pretty much covers the basics of hacking. To learn more about writing " +
"scripts using the Netscript language, select the 'Tutorial' link in the " +
"main navigation menu to look at the documentation. For now, let's move on " +
"to something else!");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.GoToHacknetNodesPage:
iTutorialSetText("Hacking is not the only way to earn money. One other way to passively " +
"earn money is by purchasing and upgrading Hacknet Nodes. Let's go to " +
"the 'Hacknet Nodes' page through the main navigation menu now.");
document.getElementById("hacknet-nodes-menu-link").setAttribute("class", "flashing-button");
var hacknetNodesButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "none";
hacknetNodesButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadHacknetNodesContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("hacknet-nodes-menu-link");
return false;
});
break;
case iTutorialSteps.HacknetNodesIntroduction:
iTutorialSetText("From this page you can purchase new Hacknet Nodes and upgrade your " +
"existing ones. Let's purchase a new one now.");
//Next step triggered by purchaseHacknet() (HacknetNode.js)
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
iTutorialSetText("You just purchased a Hacknet Node! This Hacknet Node will passively " +
"earn you money over time, both online and offline. When you get enough " +
" money, you can upgrade " +
"your newly-purchased Hacknet Node below.
" +
"Let's go to the 'City' page through the main navigation menu.");
document.getElementById("city-menu-link").setAttribute("class", "flashing-button");
var worldButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link");
worldButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadWorldContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("city-menu-link");
return false;
});
break;
case iTutorialSteps.WorldDescription:
iTutorialSetText("This page lists all of the different locations you can currently " +
"travel to. Each location has something that you can do. " +
"There's a lot of content out in the world, make sure " +
"you explore and discover!
" +
"Lastly, click on the 'Tutorial' link in the main navigation menu.");
document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button");
var tutorialButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link");
tutorialButton.addEventListener("click", function() {
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].loadTutorialContent();
iTutorialNextStep();
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("tutorial-menu-link");
return false;
});
break;
case iTutorialSteps.TutorialPageInfo:
iTutorialSetText("This page contains a lot of different documentation about the game's " +
"content and mechanics. I know it's a lot, but I highly suggest you read " +
"(or at least skim) through this before you start playing. That's the end of the tutorial. " +
"Hope you enjoy the game!");
var next = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-next");
next.style.display = "inline-block";
next.innerHTML = "Finish Tutorial";
var backButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_3__["clearEventListeners"])("interactive-tutorial-back");
backButton.style.display = "none";
next.addEventListener("click", function() {
iTutorialNextStep();
return false;
});
break;
case iTutorialSteps.End:
iTutorialEnd();
break;
default:
throw new Error("Invalid tutorial step");
}
}
//Go to the next step and evaluate it
function iTutorialNextStep() {
switch(currITutorialStep) {
case iTutorialSteps.Start:
currITutorialStep = iTutorialSteps.GoToCharacterPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.GoToCharacterPage:
document.getElementById("stats-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.CharacterPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.CharacterPage:
currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.CharacterGoToTerminalPage:
document.getElementById("terminal-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.TerminalIntro;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalIntro:
currITutorialStep = iTutorialSteps.TerminalHelp;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalHelp:
currITutorialStep = iTutorialSteps.TerminalLs;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalLs:
currITutorialStep = iTutorialSteps.TerminalScan;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalScan:
currITutorialStep = iTutorialSteps.TerminalScanAnalyze1;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalScanAnalyze1:
currITutorialStep = iTutorialSteps.TerminalScanAnalyze2;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalScanAnalyze2:
currITutorialStep = iTutorialSteps.TerminalConnect;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalConnect:
currITutorialStep = iTutorialSteps.TerminalAnalyze;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalAnalyze:
currITutorialStep = iTutorialSteps.TerminalNuke;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalNuke:
currITutorialStep = iTutorialSteps.TerminalManualHack;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalManualHack:
currITutorialStep = iTutorialSteps.TerminalHackingMechanics;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalHackingMechanics:
currITutorialStep = iTutorialSteps.TerminalCreateScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalCreateScript:
currITutorialStep = iTutorialSteps.TerminalTypeScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalTypeScript:
currITutorialStep = iTutorialSteps.TerminalFree;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalFree:
currITutorialStep = iTutorialSteps.TerminalRunScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalRunScript:
currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalGoToActiveScriptsPage:
document.getElementById("active-scripts-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.ActiveScriptsPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.ActiveScriptsPage:
document.getElementById("terminal-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal;
iTutorialEvaluateStep();
break;
case iTutorialSteps.ActiveScriptsToTerminal:
currITutorialStep = iTutorialSteps.TerminalTailScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalTailScript:
currITutorialStep = iTutorialSteps.GoToHacknetNodesPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.GoToHacknetNodesPage:
document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.HacknetNodesIntroduction;
iTutorialEvaluateStep();
break;
case iTutorialSteps.HacknetNodesIntroduction:
currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
document.getElementById("city-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.WorldDescription;
iTutorialEvaluateStep();
break;
case iTutorialSteps.WorldDescription:
document.getElementById("tutorial-menu-link").removeAttribute("class");
currITutorialStep = iTutorialSteps.TutorialPageInfo;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TutorialPageInfo:
currITutorialStep = iTutorialSteps.End;
iTutorialEvaluateStep();
break;
case iTutorialSteps.End:
break;
default:
throw new Error("Invalid tutorial step");
}
}
//Go to previous step and evaluate
function iTutorialPrevStep() {
switch(currITutorialStep) {
case iTutorialSteps.Start:
currITutorialStep = iTutorialSteps.Start;
iTutorialEvaluateStep();
break;
case iTutorialSteps.GoToCharacterPage:
currITutorialStep = iTutorialSteps.Start;
iTutorialEvaluateStep();
break;
case iTutorialSteps.CharacterPage:
currITutorialStep = iTutorialSteps.GoToCharacterPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.CharacterGoToTerminalPage:
currITutorialStep = iTutorialSteps.CharacterPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalIntro:
currITutorialStep = iTutorialSteps.CharacterGoToTerminalPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalHelp:
currITutorialStep = iTutorialSteps.TerminalIntro;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalLs:
currITutorialStep = iTutorialSteps.TerminalHelp;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalScan:
currITutorialStep = iTutorialSteps.TerminalLs;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalConnect:
currITutorialStep = iTutorialSteps.TerminalScan;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalAnalyze:
currITutorialStep = iTutorialSteps.TerminalConnect;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalNuke:
currITutorialStep = iTutorialSteps.TerminalAnalyze;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalManualHack:
currITutorialStep = iTutorialSteps.TerminalNuke;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalHackingMechanics:
currITutorialStep = iTutorialSteps.TerminalManualHack;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalCreateScript:
currITutorialStep = iTutorialSteps.TerminalManualHack;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalTypeScript:
currITutorialStep = iTutorialSteps.TerminalCreateScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalFree:
currITutorialStep = iTutorialSteps.TerminalTypeScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalRunScript:
currITutorialStep = iTutorialSteps.TerminalFree;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalGoToActiveScriptsPage:
currITutorialStep = iTutorialSteps.TerminalRunScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.ActiveScriptsPage:
currITutorialStep = iTutorialSteps.TerminalGoToActiveScriptsPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.ActiveScriptsToTerminal:
currITutorialStep = iTutorialSteps.ActiveScriptsPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TerminalTailScript:
currITutorialStep = iTutorialSteps.ActiveScriptsToTerminal;
iTutorialEvaluateStep();
break;
case iTutorialSteps.GoToHacknetNodesPage:
currITutorialStep = iTutorialSteps.TerminalTailScript;
iTutorialEvaluateStep();
break;
case iTutorialSteps.HacknetNodesIntroduction:
currITutorialStep = iTutorialSteps.GoToHacknetNodesPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.HacknetNodesGoToWorldPage:
currITutorialStep = iTutorialSteps.HacknetNodesIntroduction;
iTutorialEvaluateStep();
break;
case iTutorialSteps.WorldDescription:
currITutorialStep = iTutorialSteps.HacknetNodesGoToWorldPage;
iTutorialEvaluateStep();
break;
case iTutorialSteps.TutorialPageInfo:
currITutorialStep = iTutorialSteps.WorldDescription;
iTutorialEvaluateStep();
break;
case iTutorialSteps.End:
break;
default:
throw new Error("Invalid tutorial step");
}
}
function iTutorialEnd() {
//Re-enable auto save
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].Counters.autoSaveCounter = 300;
console.log("Ending interactive tutorial");
_engine_js__WEBPACK_IMPORTED_MODULE_0__["Engine"].init();
currITutorialStep = iTutorialSteps.End;
iTutorialIsRunning = false;
document.getElementById("interactive-tutorial-container").style.display = "none";
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_2__["dialogBoxCreate"])("If you are new to the game, the following links may be useful for you!
" +
"Getting Started Guide" +
"Wiki
" +
"The Beginner's Guide to Hacking was added to your home computer! It contains some tips/pointers for starting out with the game. " +
"To read it, go to Terminal and enter
cat hackers-starting-handbook.lit");
_Player_js__WEBPACK_IMPORTED_MODULE_1__["Player"].getHomeComputer().messages.push("hackers-starting-handbook.lit");
}
function iTutorialSetText(txt) {
var textBox = document.getElementById("interactive-tutorial-text");
if (textBox == null) {throw new Error("Could not find text box"); return;}
textBox.innerHTML = txt;
textBox.parentElement.scrollTop = 0; // this resets scroll position
}
/***/ }),
/* 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 */ 82);
/* 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 */ 83);
/* 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 */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Settings.js */ 17);
/* 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;
}
WorkerScript.prototype.shouldLog = function(fn) {
return (this.disableLogs.ALL == null && this.disableLogs[fn] == null);
}
WorkerScript.prototype.log = function(txt) {
this.scriptRef.log(txt);
}
//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 ***!
\***********************/
/***/ (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__, "updateScriptEditorContent", function() { return updateScriptEditorContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAllRunningScripts", function() { return loadAllRunningScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findRunningScript", function() { return findRunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RunningScript", function() { return RunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Script", function() { return Script; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AllServersMap", function() { return AllServersMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "scriptEditorInit", function() { return scriptEditorInit; });
/* 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 */ 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 */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Settings.js */ 17);
/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Terminal.js */ 18);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextFile */ 58);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_11__);
/* 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 */ 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__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__);
var ace = __webpack_require__(/*! brace */ 200);
var beautify = __webpack_require__(/*! js-beautify */ 199).js_beautify;
__webpack_require__(/*! brace/mode/javascript */ 197);
__webpack_require__(/*! ../netscript */ 196);
__webpack_require__(/*! brace/theme/chaos */ 195);
__webpack_require__(/*! brace/theme/chrome */ 194);
__webpack_require__(/*! brace/theme/monokai */ 193);
__webpack_require__(/*! brace/theme/solarized_dark */ 192);
__webpack_require__(/*! brace/theme/solarized_light */ 191);
__webpack_require__(/*! brace/theme/terminal */ 190);
__webpack_require__(/*! brace/theme/twilight */ 189);
__webpack_require__(/*! brace/theme/xcode */ 188);
__webpack_require__(/*! brace/keybinding/vim */ 187);
__webpack_require__(/*! brace/keybinding/emacs */ 186);
__webpack_require__(/*! brace/ext/language_tools */ 185);
// Importing this doesn't work for some reason.
const walk = __webpack_require__(/*! acorn/dist/walk */ 184);
var keybindings = {
ace: null,
vim: "ace/keyboard/vim",
emacs: "ace/keyboard/emacs",
};
function isScriptFilename(f) {
return f.endsWith(".js") || f.endsWith(".script") || f.endsWith(".ns");
}
var scriptEditorRamCheck = null, scriptEditorRamText = null;
function scriptEditorInit() {
//Create buttons at the bottom of script editor
var wrapper = document.getElementById("script-editor-buttons-wrapper");
if (wrapper == null) {
console.log("Error finding 'script-editor-buttons-wrapper'");
return;
}
var beautifyButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerText:"Beautify",
clickListener:()=>{
beautifyScript();
return false;
}
});
var closeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
class:"a-link-button", display:"inline-block",
innerText:"Save & Close (Ctrl/Cmd + b)",
clickListener:()=>{
saveAndCloseScriptEditor();
return false;
}
});
scriptEditorRamText = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("p", {
display:"inline-block", margin:"10px", id:"script-editor-status-text"
});
var checkboxLabel = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("label", {
for:"script-editor-ram-check", margin:"4px", marginTop: "8px",
innerText:"Dynamic RAM Usage Checker", color:"white",
tooltip:"Enable/Disable the dynamic RAM Usage display. You may " +
"want to disable it for very long scripts because there may be " +
"performance issues"
});
scriptEditorRamCheck = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("input", {
type:"checkbox", name:"script-editor-ram-check", id:"script-editor-ram-check",
margin:"4px", marginTop: "8px",
});
scriptEditorRamCheck.checked = true;
var documentationButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["createElement"])("a", {
display:"inline-block", class:"a-link-button", innerText:"Netscript Documentation",
href:"https://bitburner.readthedocs.io/en/latest/index.html",
target:"_blank"
});
wrapper.appendChild(beautifyButton);
wrapper.appendChild(closeButton);
wrapper.appendChild(scriptEditorRamText);
wrapper.appendChild(scriptEditorRamCheck);
wrapper.appendChild(checkboxLabel);
wrapper.appendChild(documentationButton);
//Initialize ACE Script editor
var editor = ace.edit('javascript-editor');
editor.getSession().setMode('ace/mode/netscript');
editor.setTheme('ace/theme/monokai');
document.getElementById('javascript-editor').style.fontSize='16px';
editor.setOption("showPrintMargin", false);
/* Script editor options */
//Theme
var themeDropdown = document.getElementById("script-editor-option-theme");
if (_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
var initialIndex = 2;
for (var i = 0; i < themeDropdown.options.length; ++i) {
if (themeDropdown.options[i].value === _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme) {
initialIndex = i;
break;
}
}
themeDropdown.selectedIndex = initialIndex;
} else {
themeDropdown.selectedIndex = 2;
}
themeDropdown.onchange = function() {
var val = themeDropdown.value;
_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorTheme = val;
var themePath = "ace/theme/" + val.toLowerCase();
editor.setTheme(themePath);
};
themeDropdown.onchange();
//Keybinding
var keybindingDropdown = document.getElementById("script-editor-option-keybinding");
if (_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
var initialIndex = 0;
for (var i = 0; i < keybindingDropdown.options.length; ++i) {
if (keybindingDropdown.options[i].value === _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding) {
initialIndex = i;
break;
}
}
keybindingDropdown.selectedIndex = initialIndex;
} else {
keybindingDropdown.selectedIndex = 0;
}
keybindingDropdown.onchange = function() {
var val = keybindingDropdown.value;
_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].EditorKeybinding = val;
editor.setKeyboardHandler(keybindings[val.toLowerCase()]);
};
keybindingDropdown.onchange();
//Highlight Active line
var highlightActiveChkBox = document.getElementById("script-editor-option-highlightactiveline");
highlightActiveChkBox.onchange = function() {
editor.setHighlightActiveLine(highlightActiveChkBox.checked);
};
//Show Invisibles
var showInvisiblesChkBox = document.getElementById("script-editor-option-showinvisibles");
showInvisiblesChkBox.onchange = function() {
editor.setShowInvisibles(showInvisiblesChkBox.checked);
};
//Use Soft Tab
var softTabChkBox = document.getElementById("script-editor-option-usesofttab");
softTabChkBox.onchange = function() {
editor.getSession().setUseSoftTabs(softTabChkBox.checked);
};
//Jshint Maxerr
var maxerr = document.getElementById("script-editor-option-maxerr");
var maxerrLabel = document.getElementById("script-editor-option-maxerror-value-label");
maxerrLabel.innerHTML = maxerr.value;
maxerr.onchange = function() {
editor.getSession().$worker.send("changeOptions", [{maxerr:maxerr.value}]);
maxerrLabel.innerHTML = maxerr.value;
}
//Configure some of the VIM keybindings
ace.config.loadModule('ace/keyboard/vim', function(module) {
var VimApi = module.CodeMirror.Vim;
VimApi.defineEx('write', 'w', function(cm, input) {
saveAndCloseScriptEditor();
});
VimApi.defineEx('quit', 'q', function(cm, input) {
_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
});
VimApi.defineEx('xwritequit', 'x', function(cm, input) {
saveAndCloseScriptEditor();
});
VimApi.defineEx('wqwritequit', 'wq', function(cm, input) {
saveAndCloseScriptEditor();
});
});
//Function autocompleter
editor.setOption("enableBasicAutocompletion", true);
var autocompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
if (prefix.length === 0) {callback(null, []); return;}
var words = [];
var fns = Object(_NetscriptFunctions_js__WEBPACK_IMPORTED_MODULE_5__["NetscriptFunctions"])(null);
for (var name in fns) {
if (fns.hasOwnProperty(name)) {
words.push({
name: name,
value: name,
});
}
}
callback(null, words);
},
}
editor.completers = [autocompleter];
}
//Updates RAM usage in script
function updateScriptEditorContent() {
var filename = document.getElementById("script-editor-filename").value;
if (scriptEditorRamCheck == null || !scriptEditorRamCheck.checked || !isScriptFilename(filename)) {
scriptEditorRamText.innerText = "N/A";
return;
}
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
var codeCopy = code.repeat(1);
var ramUsage = calculateRamUsage(codeCopy);
if (ramUsage !== -1) {
scriptEditorRamText.innerText = "RAM: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(ramUsage, 2).toString() + "GB";
} else {
scriptEditorRamText.innerText = "RAM: Syntax Error";
}
}
//Define key commands in script editor (ctrl o to save + close, etc.)
$(document).keydown(function(e) {
if (_Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].DisableHotkeys === true) {return;}
if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) {
//Ctrl + b
if (e.keyCode == 66 && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
saveAndCloseScriptEditor();
}
}
});
function beautifyScript() {
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
code = beautify(code, { indent_size: 4 })
editor.setValue(code);
}
function saveAndCloseScriptEditor() {
var filename = document.getElementById("script-editor-filename").value;
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
if (_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialIsRunning"] && _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["currITutorialStep"] == _InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialSteps"].TerminalTypeScript) {
if (filename != "foodnstuff.script") {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Leave the script name as 'foodnstuff'!");
return;
}
code = code.replace(/\s/g, "");
if (code.indexOf("while(true){hack('foodnstuff');}") == -1) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Please copy and paste the code from the tutorial!");
return;
}
Object(_InteractiveTutorial_js__WEBPACK_IMPORTED_MODULE_3__["iTutorialNextStep"])();
}
if (filename == "") {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("You must specify a filename!");
return;
}
if (checkValidFilename(filename) == false) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Script filename can contain only alphanumerics, hyphens, and underscores");
return;
}
var s = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer();
if (filename === ".fconf") {
try {
Object(_Fconf_js__WEBPACK_IMPORTED_MODULE_2__["parseFconfSettings"])(code);
} catch(e) {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid .fconf file");
return;
}
} else if (isScriptFilename(filename)) {
//If the current script already exists on the server, overwrite it
for (var i = 0; i < s.scripts.length; i++) {
if (filename == s.scripts[i].filename) {
s.scripts[i].saveScript();
_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
return;
}
}
//If the current script does NOT exist, create a new one
var script = new Script();
script.saveScript();
s.scripts.push(script);
} else if (filename.endsWith(".txt")) {
for (var i = 0; i < s.textFiles.length; ++i) {
if (s.textFiles[i].fn === filename) {
s.textFiles[i].write(code);
_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
return;
}
}
var textFile = new _TextFile__WEBPACK_IMPORTED_MODULE_11__["TextFile"](filename, code);
s.textFiles.push(textFile);
} else {
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_13__["dialogBoxCreate"])("Invalid filename. Must be either a script (.script) or " +
" or text file (.txt)")
return;
}
_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].loadTerminalContent();
}
//Checks that the string contains only valid characters for a filename, which are alphanumeric,
// underscores, hyphens, and dots
function checkValidFilename(filename) {
var regex = /^[.a-zA-Z0-9_-]+$/;
if (filename.match(regex)) {
return true;
}
return false;
}
function Script() {
this.filename = "";
this.code = "";
this.ramUsage = 0;
this.server = ""; //IP of server this script is on
this.module = "";
};
//Get the script data from the Script Editor and save it to the object
Script.prototype.saveScript = function() {
if (_engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].currentPage == _engine_js__WEBPACK_IMPORTED_MODULE_1__["Engine"].Page.ScriptEditor) {
//Update code and filename
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
this.code = code.replace(/^\s+|\s+$/g, '');
var filename = document.getElementById("script-editor-filename").value;
this.filename = filename;
//Server
this.server = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].currentServer;
//Calculate/update ram usage, execution time, etc.
this.updateRamUsage();
this.module = "";
}
}
//Updates how much RAM the script uses when it is running.
Script.prototype.updateRamUsage = function() {
var codeCopy = this.code.repeat(1);
var res = calculateRamUsage(codeCopy);
if (res !== -1) {
this.ramUsage = res;
}
}
// These special strings are used to reference the presence of a given logical
// construct within a user script.
const specialReferenceIF = "__SPECIAL_referenceIf";
const specialReferenceFOR = "__SPECIAL_referenceFor";
const specialReferenceWHILE = "__SPECIAL_referenceWhile";
// The global scope of a script is registered under this key during parsing.
const memCheckGlobalKey = ".__GLOBAL__";
// Calcluates the amount of RAM a script uses. Uses parsing and AST walking only,
// rather than NetscriptEvaluator. This is useful because NetscriptJS code does
// not work under NetscriptEvaluator.
function parseOnlyRamCalculate(server, code, workerScript) {
try {
// Maps dependent identifiers to their dependencies.
//
// The initial identifier is __SPECIAL_INITIAL_MODULE__.__GLOBAL__.
// It depends on all the functions declared in the module, all the global scopes
// of its imports, and any identifiers referenced in this global scope. Each
// function depends on all the identifiers referenced internally.
// We walk the dependency graph to calculate RAM usage, given that some identifiers
// reference Netscript functions which have a RAM cost.
let dependencyMap = {};
// Scripts we've parsed.
const completedParses = new Set();
// Scripts we've discovered that need to be parsed.
const parseQueue = [];
// Parses a chunk of code with a given module name, and updates parseQueue and dependencyMap.
function parseCode(code, moduleName) {
const result = parseOnlyCalculateDeps(code, moduleName);
completedParses.add(moduleName);
// Add any additional modules to the parse queue;
for (let i = 0; i < result.additionalModules.length; ++i) {
if (!completedParses.has(result.additionalModules[i])) {
parseQueue.push(result.additionalModules[i]);
}
}
// Splice all the references in.
dependencyMap = {...dependencyMap, ...result.dependencyMap};
}
const initialModule = "__SPECIAL_INITIAL_MODULE__";
parseCode(code, initialModule);
while (parseQueue.length > 0) {
// Get the code from the server.
const nextModule = parseQueue.shift();
const script = server.getScript(nextModule);
if (!script) return -1; // No such script on the server.
// Not sure why we always take copies, but let's do that here too.
parseCode(script.code.repeat(1), nextModule);
}
// Finally, walk the reference map and generate a ram cost. The initial set of keys to scan
// are those that start with __SPECIAL_INITIAL_MODULE__.
let ram = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptBaseRamCost;
const unresolvedRefs = Object.keys(dependencyMap).filter(s => s.startsWith(initialModule));
const resolvedRefs = new Set();
while (unresolvedRefs.length > 0) {
const ref = unresolvedRefs.shift();
resolvedRefs.add(ref);
if (ref.endsWith(".*")) {
// A prefix reference. We need to find all matching identifiers.
const prefix = ref.slice(0, ref.length - 2);
for (let ident of Object.keys(dependencyMap).filter(k => k.startsWith(prefix))) {
for (let dep of dependencyMap[ident] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
}
}
} else {
// An exact reference. Add all dependencies of this ref.
for (let dep of dependencyMap[ref] || []) {
if (!resolvedRefs.has(dep)) unresolvedRefs.push(dep);
}
}
// Check if this is one of the special keys, and add the appropriate ram cost if so.
if (ref == specialReferenceIF) ram += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost;
if (ref == specialReferenceFOR) ram += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost;
if (ref == specialReferenceWHILE) ram += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptWhileRamCost;
if (ref == "hacknetnodes") ram += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost;
if (ref == "document" || ref == "window") ram += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptDomRamCost;
// Check if this ident is a function in the workerscript env. If it is, then we need to
// get its RAM cost. We do this by calling it, which works because the running script
// is in checkingRam mode.
//
// TODO it would be simpler to just reference a dictionary.
try {
function applyFuncRam(func) {
if (typeof func === "function") {
try {
let res = func.apply(null, []);
if (typeof res === "number") {
return res;
}
return 0;
} catch(e) {
console.log("ERROR applying function: " + e);
return 0;
}
} else {
return 0;
}
}
//Special logic for Bladeburner
var func;
if (ref in workerScript.env.vars.bladeburner) {
func = workerScript.env.vars.bladeburner[ref];
} else {
func = workerScript.env.get(ref);
}
ram += applyFuncRam(func);
} catch (error) {continue;}
}
return ram;
} catch (error) {
console.info("parse or eval error: ", error);
// This is not unexpected. The user may be editing a script, and it may be in
// a transitory invalid state.
return -1;
}
}
// Parses one script and calculates its ram usage, for the global scope and each function.
// Returns a cost map and a dependencyMap for the module. Returns a reference map to be joined
// onto the main reference map, and a list of modules that need to be parsed.
function parseOnlyCalculateDeps(code, currentModule) {
const ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["parse"])(code, {sourceType:"module", ecmaVersion: 8});
// Everything from the global scope goes in ".". Everything else goes in ".function", where only
// the outermost layer of functions counts.
const globalKey = currentModule + memCheckGlobalKey;
const dependencyMap = {};
dependencyMap[globalKey] = new Set();
// If we reference this internal name, we're really referencing that external name.
// Filled when we import names from other modules.
let internalToExternal = {};
var additionalModules = [];
// References get added pessimistically. They are added for thisModule.name, name, and for
// any aliases.
function addRef(key, name) {
const s = dependencyMap[key] || (dependencyMap[key] = new Set());
if (name in internalToExternal) {
s.add(internalToExternal[name]);
}
s.add(currentModule + "." + name);
s.add(name); // For builtins like hack.
}
//A list of identifiers that resolve to "native Javascript code"
const objectPrototypeProperties = Object.getOwnPropertyNames(Object.prototype);
// If we discover a dependency identifier, state.key is the dependent identifier.
// walkDeeper is for doing recursive walks of expressions in composites that we handle.
function commonVisitors() {
return {
Identifier: (node, st, walkDeeper) => {
if (objectPrototypeProperties.includes(node.name)) {return;}
addRef(st.key, node.name);
},
WhileStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceWHILE);
node.test && walkDeeper(node.test, st);
node.body && walkDeeper(node.body, st);
},
DoWhileStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceWHILE);
node.test && walkDeeper(node.test, st);
node.body && walkDeeper(node.body, st);
},
ForStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceFOR);
node.init && walkDeeper(node.init, st);
node.test && walkDeeper(node.test, st);
node.update && walkDeeper(node.update, st);
node.body && walkDeeper(node.body, st);
},
IfStatement: (node, st, walkDeeper) => {
addRef(st.key, specialReferenceIF);
node.test && walkDeeper(node.test, st);
node.consequent && walkDeeper(node.consequent, st);
node.alternate && walkDeeper(node.alternate, st);
},
MemberExpression: (node, st, walkDeeper) => {
node.object && walkDeeper(node.object, st);
node.property && walkDeeper(node.property, st);
},
}
}
walk.recursive(ast, {key: globalKey}, {
ImportDeclaration: (node, st, walkDeeper) => {
const importModuleName = node.source.value;
additionalModules.push(importModuleName);
// This module's global scope refers to that module's global scope, no matter how we
// import it.
dependencyMap[st.key].add(importModuleName + memCheckGlobalKey);
for (let i = 0; i < node.specifiers.length; ++i) {
const spec = node.specifiers[i];
if (spec.imported !== undefined && spec.local !== undefined) {
// We depend on specific things.
internalToExternal[spec.local.name] = importModuleName + "." + spec.imported.name;
} else {
// We depend on everything.
dependencyMap[st.key].add(importModuleName + ".*");
}
}
},
FunctionDeclaration: (node, st, walkDeeper) => {
// Don't use walkDeeper, because we are changing the visitor set.
const key = currentModule + "." + node.id.name;
walk.recursive(node, {key: key}, commonVisitors());
},
...commonVisitors()
});
return {dependencyMap: dependencyMap, additionalModules: additionalModules};
}
function calculateRamUsage(codeCopy) {
//Create a temporary/mock WorkerScript and an AST from the code
var currServ = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].getCurrentServer();
var workerScript = new _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__["WorkerScript"]({
filename:"foo",
scriptRef: {code:""},
args:[]
});
workerScript.checkingRam = true; //Netscript functions will return RAM usage
workerScript.serverIp = currServ.ip;
try {
return parseOnlyRamCalculate(currServ, codeCopy, workerScript);
} catch (e) {
console.log("Failed to parse ram using new method. Falling back.", e);
}
// Try the old way.
try {
var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["parse"])(codeCopy, {sourceType:"module"});
} catch(e) {
return -1;
}
//Search through AST, scanning for any 'Identifier' nodes for functions, or While/For/If nodes
var queue = [], ramUsage = _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptBaseRamCost;
var whileUsed = false, forUsed = false, ifUsed = false;
queue.push(ast);
while (queue.length != 0) {
var exp = queue.shift();
switch (exp.type) {
case "ImportDeclaration":
//Gets an array of all imported functions as AST expressions
//and pushes them on the queue.
var res = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_4__["evaluateImport"])(exp, workerScript, true);
for (var i = 0; i < res.length; ++i) {
queue.push(res[i]);
}
break;
case "BlockStatement":
case "Program":
for (var i = 0; i < exp.body.length; ++i) {
if (exp.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
queue.push(exp.body[i]);
}
}
break;
case "WhileStatement":
if (!whileUsed) {
ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptWhileRamCost;
whileUsed = true;
}
break;
case "ForStatement":
if (!forUsed) {
ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptForRamCost;
forUsed = true;
}
break;
case "IfStatement":
if (!ifUsed) {
ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptIfRamCost;
ifUsed = true;
}
break;
case "Identifier":
if (exp.name in workerScript.env.vars) {
var func = workerScript.env.get(exp.name);
if (typeof func === "function") {
try {
var res = func.apply(null, []);
if (typeof res === "number") {
ramUsage += res;
}
} catch(e) {
console.log("ERROR applying function: " + e);
}
}
}
break;
default:
break;
}
for (var prop in exp) {
if (exp.hasOwnProperty(prop)) {
if (exp[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_12__["Node"]) {
queue.push(exp[prop]);
}
}
}
}
//Special case: hacknetnodes array
if (codeCopy.includes("hacknetnodes")) {
ramUsage += _Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ScriptHacknetNodesRamCost;
}
return ramUsage;
}
Script.prototype.download = function() {
var filename = this.filename + ".js";
var file = new Blob([this.code], {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 = filename;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
Script.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("Script", this);
}
Script.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(Script, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.Script = Script;
//Called when the game is loaded. Loads all running scripts (from all servers)
//into worker scripts so that they will start running
function loadAllRunningScripts() {
var count = 0;
var total = 0;
let skipScriptLoad = (window.location.href.toLowerCase().indexOf("?noscripts") !== -1);
if (skipScriptLoad) {console.log("Skipping the load of any scripts during startup");}
for (var property in _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
if (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(property)) {
var server = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][property];
//Reset each server's RAM usage to 0
server.ramUsed = 0;
//Reset modules on all scripts
for (var i = 0; i < server.scripts.length; ++i) {
server.scripts[i].module = "";
}
if (skipScriptLoad) {
//Start game with no scripts
server.runningScripts.length = 0;
} else {
for (var j = 0; j < server.runningScripts.length; ++j) {
count++;
server.runningScripts[j].scriptRef.module = "";
Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_6__["addWorkerScript"])(server.runningScripts[j], server);
//Offline production
total += scriptCalculateOfflineProduction(server.runningScripts[j]);
}
}
}
}
return total;
console.log("Loaded " + count.toString() + " running scripts");
}
function scriptCalculateOfflineProduction(runningScriptObj) {
//The Player object stores the last update time from when we were online
var thisUpdate = new Date().getTime();
var lastUpdate = _Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].lastUpdate;
var timePassed = (thisUpdate - lastUpdate) / 1000; //Seconds
console.log("Offline for " + timePassed + " seconds");
//Calculate the "confidence" rating of the script's true production. This is based
//entirely off of time. We will arbitrarily say that if a script has been running for
//4 hours (14400 sec) then we are completely confident in its ability
var confidence = (runningScriptObj.onlineRunningTime) / 14400;
if (confidence >= 1) {confidence = 1;}
//Data map: [MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
//Grow
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][2] == 0 || runningScriptObj.dataMap[ip][2] == null) {continue;}
var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
if (serv == null) {continue;}
var timesGrown = Math.round(0.5 * runningScriptObj.dataMap[ip][2] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
runningScriptObj.log("Called grow() on " + serv.hostname + " " + timesGrown + " times while offline");
var growth = Object(_Server_js__WEBPACK_IMPORTED_MODULE_8__["processSingleServerGrowth"])(serv, timesGrown * 450);
runningScriptObj.log(serv.hostname + " grown by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_16__["formatNumber"])(growth * 100 - 100, 6) + "% from grow() calls made while offline");
}
}
var totalOfflineProduction = 0;
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][0] == 0 || runningScriptObj.dataMap[ip][0] == null) {continue;}
var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
if (serv == null) {continue;}
var production = 0.5 * runningScriptObj.dataMap[ip][0] / runningScriptObj.onlineRunningTime * timePassed;
production *= confidence;
if (production > serv.moneyAvailable) {
production = serv.moneyAvailable;
}
totalOfflineProduction += production;
_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gainMoney(production);
console.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
runningScriptObj.log(runningScriptObj.filename + " generated $" + production + " while offline by hacking " + serv.hostname);
serv.moneyAvailable -= production;
if (serv.moneyAvailable < 0) {serv.moneyAvailable = 0;}
if (isNaN(serv.moneyAvailable)) {serv.moneyAvailable = 0;}
}
}
//Offline EXP gain
//A script's offline production will always be at most half of its online production.
var expGain = 0.5 * (runningScriptObj.onlineExpGained / runningScriptObj.onlineRunningTime) * timePassed;
expGain *= confidence;
_Player_js__WEBPACK_IMPORTED_MODULE_7__["Player"].gainHackingExp(expGain);
//Update script stats
runningScriptObj.offlineMoneyMade += totalOfflineProduction;
runningScriptObj.offlineRunningTime += timePassed;
runningScriptObj.offlineExpGained += expGain;
//Fortify a server's security based on how many times it was hacked
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][1] == 0 || runningScriptObj.dataMap[ip][1] == null) {continue;}
var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
if (serv == null) {continue;}
var timesHacked = Math.round(0.5 * runningScriptObj.dataMap[ip][1] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " hacked " + serv.hostname + " " + timesHacked + " times while offline");
runningScriptObj.log("Hacked " + serv.hostname + " " + timesHacked + " times while offline");
serv.fortify(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerFortifyAmount * timesHacked);
}
}
//Weaken
for (var ip in runningScriptObj.dataMap) {
if (runningScriptObj.dataMap.hasOwnProperty(ip)) {
if (runningScriptObj.dataMap[ip][3] == 0 || runningScriptObj.dataMap[ip][3] == null) {continue;}
var serv = _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip];
if (serv == null) {continue;}
var timesWeakened = Math.round(0.5 * runningScriptObj.dataMap[ip][3] / runningScriptObj.onlineRunningTime * timePassed);
console.log(runningScriptObj.filename + " called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
runningScriptObj.log("Called weaken() on " + serv.hostname + " " + timesWeakened + " times while offline");
serv.weaken(_Constants_js__WEBPACK_IMPORTED_MODULE_0__["CONSTANTS"].ServerWeakenAmount * timesWeakened);
}
}
return totalOfflineProduction;
}
//Returns a RunningScript object matching the filename and arguments on the
//designated server, and false otherwise
function findRunningScript(filename, args, server) {
for (var i = 0; i < server.runningScripts.length; ++i) {
if (server.runningScripts[i].filename == filename &&
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_15__["compareArrays"])(server.runningScripts[i].args, args)) {
return server.runningScripts[i];
}
}
return null;
}
function RunningScript(script, args) {
if (script == null || script == undefined) {return;}
this.filename = script.filename;
this.args = args;
this.scriptRef = script;
this.server = script.server; //IP Address only
this.logs = []; //Script logging. Array of strings, with each element being a log entry
this.logUpd = false;
//Stats to display on the Scripts menu, and used to determine offline progress
this.offlineRunningTime = 0.01; //Seconds
this.offlineMoneyMade = 0;
this.offlineExpGained = 0;
this.onlineRunningTime = 0.01; //Seconds
this.onlineMoneyMade = 0;
this.onlineExpGained = 0;
this.threads = 1;
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
RunningScript.prototype.log = function(txt) {
if (this.logs.length > _Settings_js__WEBPACK_IMPORTED_MODULE_9__["Settings"].MaxLogCapacity) {
//Delete first element and add new log entry to the end.
//TODO Eventually it might be better to replace this with circular array
//to improve performance
this.logs.shift();
}
let logEntry = txt;
if (_Fconf_js__WEBPACK_IMPORTED_MODULE_2__["FconfSettings"].ENABLE_TIMESTAMPS) {
logEntry = "[" + _Terminal_js__WEBPACK_IMPORTED_MODULE_10__["Terminal"].getTimestamp() + "] " + logEntry;
}
this.logs.push(logEntry);
this.logUpd = true;
}
RunningScript.prototype.displayLog = function() {
for (var i = 0; i < this.logs.length; ++i) {
Object(_Terminal_js__WEBPACK_IMPORTED_MODULE_10__["post"])(this.logs[i]);
}
}
RunningScript.prototype.clearLog = function() {
this.logs.length = 0;
}
//Update the moneyStolen and numTimesHack maps when hacking
RunningScript.prototype.recordHack = function(serverIp, moneyGained, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][0] += moneyGained;
this.dataMap[serverIp][1] += n;
}
//Update the grow map when calling grow()
RunningScript.prototype.recordGrow = function(serverIp, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][2] += n;
}
//Update the weaken map when calling weaken() {
RunningScript.prototype.recordWeaken = function(serverIp, n=1) {
if (this.dataMap == null) {
//[MoneyStolen, NumTimesHacked, NumTimesGrown, NumTimesWeaken]
this.dataMap = new AllServersMap([0, 0, 0, 0], true);
}
this.dataMap[serverIp][3] += n;
}
RunningScript.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("RunningScript", this);
}
RunningScript.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(RunningScript, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.RunningScript = RunningScript;
//Creates an object that creates a map/dictionary with the IP of each existing server as
//a key. Initializes every key with a specified value that can either by a number or an array
function AllServersMap(arr=false, filterOwned=false) {
for (var ip in _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"]) {
if (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"].hasOwnProperty(ip)) {
if (filterOwned && (_Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].purchasedByPlayer || _Server_js__WEBPACK_IMPORTED_MODULE_8__["AllServers"][ip].hostname === "home")) {
continue;
}
if (arr) {
this[ip] = [0, 0, 0, 0];
} else {
this[ip] = 0;
}
}
}
}
AllServersMap.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_toJSON"])("AllServersMap", this);
}
AllServersMap.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Generic_fromJSON"])(AllServersMap, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_14__["Reviver"].constructors.AllServersMap = AllServersMap;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! jquery */ 37)))
/***/ }),
/* 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 */ 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(" ");
}
/***/ }),
/* 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 */ 15);
/* harmony import */ var _BitNode_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./BitNode.js */ 13);
/* 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 */ 35);
/* 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 */ 20);
/* harmony import */ var _DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./DarkWeb.js */ 59);
/* harmony import */ var _engine_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./engine.js */ 5);
/* harmony import */ var _Gang_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Gang.js */ 33);
/* harmony import */ var _Faction_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Faction.js */ 9);
/* harmony import */ var _HacknetNode_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./HacknetNode.js */ 40);
/* harmony import */ var _Location_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Location.js */ 4);
/* harmony import */ var _Message_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Message.js */ 27);
/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Missions.js */ 41);
/* harmony import */ var _Player_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Player.js */ 0);
/* harmony import */ var _Script_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Script.js */ 24);
/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Server.js */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Settings.js */ 17);
/* harmony import */ var _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./SpecialServerIps.js */ 16);
/* harmony import */ var _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./StockMarket.js */ 29);
/* harmony import */ var _Terminal_js__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Terminal.js */ 18);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./TextFile */ 58);
/* harmony import */ var _TextFile__WEBPACK_IMPORTED_MODULE_23___default = /*#__PURE__*/__webpack_require__.n(_TextFile__WEBPACK_IMPORTED_MODULE_23__);
/* harmony import */ var _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./NetscriptWorker.js */ 22);
/* harmony import */ var _NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./NetscriptEvaluator.js */ 31);
/* harmony import */ var _NetscriptEnvironment_js__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./NetscriptEnvironment.js */ 82);
/* harmony import */ var _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./NetscriptPort.js */ 65);
/* harmony import */ var decimal_js__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! decimal.js */ 19);
/* harmony import */ var _utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../utils/DialogBox.js */ 6);
/* harmony import */ var _utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../utils/HelperFunctions.js */ 1);
/* harmony import */ var _utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../utils/IPAddress.js */ 14);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__);
/* harmony import */ var _utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../utils/YesNoBox.js */ 12);
var sprintf = __webpack_require__(/*! sprintf-js */ 116).sprintf,
vsprintf = __webpack_require__(/*! sprintf-js */ 116).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,
run:true,
exec: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,
startAction: true,
upgradeSkill: true,
setTeamSize: true,
joinBladeburnerFaction: 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_16__["Player"].sourceFiles.length; ++i) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 3) {hasCorporationSF = true;}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 4) {
hasSingularitySF = true;
singularitySFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].lvl;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 5) {hasAISF = true;}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 6) {hasBladeburnerSF = true;}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 7) {hasBladeburner2079SF = true;}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].n === 8) {
hasWallStreetSF = true;
wallStreetSFLvl = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].sourceFiles[i].lvl;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_25__["makeRuntimeRejectMsg"])(workerScript,
"Dynamic RAM usage calculated to be greater than initial RAM usage on fn: " + fnName +
". 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_16__["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_18__["getServer"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["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_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
}
//Calculate the hacking time
var hackingTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access");
}
if (server.requiredHackingSkill > _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_25__["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_25__["netscriptDelay"])(hackingTime* 1000, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
var hackChance = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateHackingChance"])(server);
var rand = Math.random();
var expGainedOnSuccess = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateExpGain"])(server) * threads;
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
var moneyGained = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].gainMoney(moneyGained);
workerScript.scriptRef.onlineMoneyMade += moneyGained;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].scriptProdSinceLastAug += moneyGained;
workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(moneyGained, 2) + " and " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_16__["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__WEBPACK_IMPORTED_MODULE_32__["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_25__["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_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access");
}
var growTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateGrowTime"])(server);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.grow == null) {
workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(growTime/1000, 3) + " seconds (t=" + threads + ")");
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["netscriptDelay"])(growTime, workerScript).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
const moneyBefore = server.moneyAvailable;
server.moneyAvailable += (1 * threads); //It can be grown even if it has no money
var growthPercentage = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["processSingleServerGrowth"])(server, 450 * threads);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.ip, threads);
var expGain = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])((moneyAfter/moneyBefore)*100 - 100, 6) + "%. Gained " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads +")");
}
workerScript.scriptRef.onlineExpGained += expGain;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].gainHackingExp(expGain);
return Promise.resolve(moneyAfter/moneyBefore);
});
},
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_25__["makeRuntimeRejectMsg"])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access");
}
var weakenTime = Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["scriptCalculateWeakenTime"])(server);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.weaken == null) {
workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(weakenTime/1000, 3) + " seconds (t=" + threads + ")");
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["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__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(expGain, 4) + " hacking exp (t=" + threads + ")");
}
workerScript.scriptRef.onlineExpGained += expGain;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument");
}
var x = args.toString();
if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isHTML"])(x)) {
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].takeDamage(1);
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_29__["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_22__["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_25__["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_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].NukeProgram.name)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].BruteSSHProgram.name)) {
workerScript.scriptRef.log("You do not have the BruteSSH.exe program!");
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].FTPCrackProgram.name)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].RelaySMTPProgram.name)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].HTTPWormProgram.name)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"].SQLInjectProgram.name)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["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_25__["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_18__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["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_25__["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_18__["getServer"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip);
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "Invalid scriptname or numThreads argument passed to spawn()");
}
setTimeout(()=>{
if (scriptname === undefined) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "spawn() call has incorrect number of arguments. Usage: spawn(scriptname, numThreads, [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["runScriptFromScript"])(scriptServer, scriptname, argsForNewScript, workerScript, threads);
}, 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_25__["makeRuntimeRejectMsg"])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_17__["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_30__["printArray"])(argsForKillTarget));
return false;
}
var res = Object(_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_24__["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_30__["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_30__["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_25__["makeRuntimeRejectMsg"])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_24__["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 0;}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_24__["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_25__["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_17__["isScriptFilename"])(scriptname) &&
!scriptname.endsWith("txt")) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip2);
if (destServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip);
}
currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip1);
if (currServ == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: scp() call has incorrect number of arguments. Takes 2 or 3 arguments");
}
destServer = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip1);
if (destServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid hostname/ip passed into scp() command: " + ip);
}
currServ = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp);
if (currServ == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_14__["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__WEBPACK_IMPORTED_MODULE_23__["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_17__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ls() failed because of invalid arguments. Usage: ls(ip/hostname, [grep filter])");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("ls() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_14__["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_14__["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;
},
ps : function(ip=workerScript.serverIp) {
if (workerScript.checkingRam) {
return updateStaticRam("ps", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost);
}
updateDynamicRam("ps", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptScanRamCost);
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null){
workerScript.scriptRef.log("ps() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ps() failed. Invalid IP or hostname passed in: " + ip);
}
const processes = [];
for(const i in server.runningScripts) {
const script = server.runningScripts[i];
processes.push({filename:script.filename, threads: script.threads, args: script.args.slice()})
}
return processes;
},
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_25__["makeRuntimeRejectMsg"])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null){
workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].updateSkillLevels();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getHackingLevel == null) {
workerScript.scriptRef.log("getHackingLevel() returned " + _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_skill);
}
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].hacking_chance_mult,
speed: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_speed_mult,
money: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacking_money_mult,
growth: _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].hacknet_node_money_mult,
purchaseCost: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_purchase_cost_mult,
ramCost: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_ram_cost_mult,
coreCost: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hacknet_node_core_cost_mult,
levelCost: _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_25__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMoneyAvailable() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].money.toNumber(), 2));
}
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].money.toNumber();
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.getServerMoneyAvailable == null) {
workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMinSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(server.maxRam, 2) + "GB, " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_18__["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_25__["makeRuntimeRejectMsg"])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_14__["Message"]) &&
filename.toLowerCase() === server.messages[i]) {
return true;
}
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["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_25__["makeRuntimeRejectMsg"])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_17__["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_12__["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_12__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()");
}
var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()");
}
var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use buyStock()");
}
var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].money.lt(totalPrice + _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].StockMarketCommission)) {
workerScript.scriptRef.log("Not enough money to purchase " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " +
symbol + ". Need $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_16__["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_21__["updateStockPlayerPosition"])(stock);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.buyStock == null) {
workerScript.scriptRef.log("Bought " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellStock()");
}
var stock = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["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_16__["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_21__["updateStockPlayerPosition"])(stock);
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.sellStock == null) {
workerScript.scriptRef.log("Sold " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(stock.price, 2) + " per share. Gained " +
"$" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use shortStock()");
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into shortStock()");
}
var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use sellShort()");
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into sellShort()");
}
var res = Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use placeOrder()");
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["OrderTypes"].LimitBuy;
} else if (type.includes("limit") && type.includes("sell")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitSell;
} else if (type.includes("stop") && type.includes("buy")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopBuy;
} else if (type.includes("stop") && type.includes("sell")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopSell;
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
}
pos = pos.toLowerCase();
if (pos.includes("l")) {
orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Long;
} else if (pos.includes('s')) {
orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Short;
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Position Type passed into placeOrder()");
}
return Object(_StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["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_16__["Player"].hasTixApiAccess) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "You don't have TIX API Access! Cannot use cancelOrder()");
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 8) {
if (!(hasWallStreetSF && wallStreetSFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["SymbolToStockMap"][symbol];
if (stock == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid stock symbol passed into cancelOrder()");
}
if (isNaN(shares) || isNaN(price)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["OrderTypes"].LimitBuy;
} else if (type.includes("limit") && type.includes("sell")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].LimitSell;
} else if (type.includes("stop") && type.includes("buy")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopBuy;
} else if (type.includes("stop") && type.includes("sell")) {
orderType = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["OrderTypes"].StopSell;
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Invalid Order Type passed into placeOrder()");
}
pos = pos.toLowerCase();
if (pos.includes("l")) {
orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Long;
} else if (pos.includes('s')) {
orderPos = _StockMarket_js__WEBPACK_IMPORTED_MODULE_21__["PositionTypes"].Short;
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_21__["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_16__["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_30__["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_16__["Player"].money.lt(cost)) {
workerScript.scriptRef.log("ERROR: Not enough money to purchase server. Need $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["formatNumber"])(cost, 2));
return "";
}
var newServ = new _Server_js__WEBPACK_IMPORTED_MODULE_18__["Server"]({
ip: Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_31__["createRandomIp"])(),
hostname: hostnameStr,
organizationName: "",
isConnectedTo: false,
adminRights: true,
purchasedByPlayer: true,
maxRam: ram,
});
Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["AddToAllServers"])(newServ);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers.push(newServ.ip);
var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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__WEBPACK_IMPORTED_MODULE_32__["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_18__["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_16__["Player"].purchasedServers.length; ++i) {
if (ip == _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].purchasedServers[i]) {
found = true;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_18__["AllServers"][ip];
//Delete from home computer
found = false;
var homeComputer = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].purchasedServers.forEach(function(ip) {
if (hostname) {
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_24__["NetscriptPorts"][port-1];
if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.write(data);
} else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Write to text file
var fn = port;
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in write(). This is a bug please contact game dev");
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server);
if (txtFile == null) {
txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["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_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_24__["NetscriptPorts"][port-1];
if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.read();
} else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Read from text file
var fn = port;
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in read(). This is a bug please contact game dev");
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server);
if (txtFile !== null) {
return txtFile.text;
} else {
return "";
}
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_24__["NetscriptPorts"][port-1];
if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_24__["NetscriptPorts"][port-1];
if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: Could not find port: " + port + ". This is a bug contact the game developer");
}
return port.clear();
} else if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(port)) { //Clear text file
var fn = port;
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(workerScript.serverIp);
if (server == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Error getting Server for this script in clear(). This is a bug please contact game dev");
}
var txtFile = Object(_TextFile__WEBPACK_IMPORTED_MODULE_23__["getTextFile"])(fn, server);
if (txtFile != null) {
txtFile.write("");
}
} else {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_24__["NetscriptPorts"][port-1];
if (port == null || !(port instanceof _NetscriptPort_js__WEBPACK_IMPORTED_MODULE_27__["NetscriptPort"])) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: 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_18__["getServer"])(workerScript.serverIp);
if (s == null) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_17__["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_14__["Message"]) && Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_24__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].scriptProdSinceLastAug / (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].playtimeSinceLastAug/1000));
return res;
} else {
//Get income for a particular script
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptIncome() failed. Invalid IP or hostnamed passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_17__["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_30__["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_24__["workerScripts"].length; ++i) {
total += (_NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_24__["workerScripts"][i].scriptRef.onlineExpGained / _NetscriptWorker_js__WEBPACK_IMPORTED_MODULE_24__["workerScripts"][i].scriptRef.onlineRunningTime);
}
return total;
} else {
//Get income for a particular script
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["getServer"])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptExpGain() failed. Invalid IP or hostnamed passed in: " + ip);
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_17__["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_30__["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_16__["Player"].playtimeSinceLastAug;
},
prompt : function(txt) {
if (workerScript.checkingRam) {return 0;}
if (_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxOpen"]) {
workerScript.scriptRef.log("ERROR: confirm() failed because a pop-up dialog box is already open");
return false;
}
if (!Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(txt)) {txt = String(txt);}
var yesBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxGetYesButton"])(), noBtn = Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxGetNoButton"])();
yesBtn.innerHTML = "Yes";
noBtn.innerHTML = "No";
return new Promise(function(resolve, reject) {
yesBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxClose"])();
resolve(true);
});
noBtn.addEventListener("click", ()=>{
Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxClose"])();
resolve(false);
});
Object(_utils_YesNoBox_js__WEBPACK_IMPORTED_MODULE_33__["yesNoBoxCreate"])(txt);
});
},
/* Singularity Functions */
universityCourse : function(universityName, className) {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("universityCourse", ramCost);
}
updateDynamicRam("universityCourse", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: universityCourse() failed because you are in the middle of a mission.");
return;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_13__["Locations"].AevumSummitUniversity.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSummitUniversity;
costMult = 4;
expMult = 3;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12RothmanUniversity;
costMult = 3;
expMult = 2;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenZBInstituteOfTechnology.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("gymWorkout", ramCost);
}
updateDynamicRam("gymWorkout", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: gymWorkout() failed because you are in the middle of a mission.");
return;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_13__["Locations"].AevumCrushFitnessGym.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumCrushFitnessGym;
costMult = 3;
expMult = 2;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSnapFitnessGym;
costMult = 10;
expMult = 5;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12IronGym;
costMult = 1;
expMult = 1;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym.toLowerCase():
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12PowerhouseGym;
costMult = 20;
expMult = 10;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].VolhavenMilleniumFitnessGym:
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city != _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_16__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymStrength);
break;
case "defense".toLowerCase():
case "def".toLowerCase():
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDefense);
break;
case "dexterity".toLowerCase():
case "dex".toLowerCase():
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].startClass(costMult, expMult, _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ClassGymDexterity);
break;
case "agility".toLowerCase():
case "agi".toLowerCase():
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("travelToCity", ramCost);
}
updateDynamicRam("travelToCity", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_13__["Locations"].Aevum:
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing:
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12:
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo:
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima:
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven:
if(_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_25__["makeRuntimeRejectMsg"])(workerScript, "ERROR: not enough money to travel with travelToCity().");
}
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TravelCost);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city = cityname;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseTor", ramCost);
}
updateDynamicRam("purchaseTor", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_20__["SpecialServerIps"]["Darkweb Server"] != null) {
workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed");
return false;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].loseMoney(_Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].TorRouterCost);
var darkweb = new _Server_js__WEBPACK_IMPORTED_MODULE_18__["Server"]({
ip:Object(_utils_IPAddress_js__WEBPACK_IMPORTED_MODULE_31__["createRandomIp"])(), hostname:"darkweb", organizationName:"",
isConnectedTo:false, adminRights:false, purchasedByPlayer:false, maxRam:1
});
Object(_Server_js__WEBPACK_IMPORTED_MODULE_18__["AddToAllServers"])(darkweb);
_SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"].addIp("Darkweb Server", darkweb.ip);
const purchaseTor = document.getElementById("location-purchase-tor");
purchaseTor.setAttribute("class", "a-link-button-bought");
purchaseTor.innerHTML = "TOR Router - Purchased";
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().ip);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseProgram", ramCost);
}
updateDynamicRam("purchaseProgram", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_20__["SpecialServerIps"]["Darkweb Server"] == null) {
workerScript.scriptRef.log("ERROR: You do not have the TOR router. purchaseProgram() failed.");
return false;
}
programName = programName.toLowerCase();
let item = null;
for(const key in _DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"]) {
const i = _DarkWeb_js__WEBPACK_IMPORTED_MODULE_8__["DarkWebItems"][key];
if(i.program.toLowerCase() == programName) {
item = i;
}
}
if(item == null) {
workerScript.scriptRef.log("ERROR: Invalid program name passed into purchaseProgram().");
return false;
}
if(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].money.lt(item.price)) {
workerScript.scriptRef.log("Not enough money to purchase " + item.program);
return false;
}
if(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(item.program)) {
workerScript.scriptRef.log('You already have the '+item.program+' program');
return true;
}
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(item.price);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getHomeComputer().programs.push(item.program);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.purchaseProgram == null) {
workerScript.scriptRef.log("You have purchased the "+item.program+" program. The new program can be found on your home computer.");
}
return true;
},
getStats : function() {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getStats", ramCost);
}
updateDynamicRam("getStats", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].hacking_skill,
strength: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].strength,
defense: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].defense,
dexterity: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].dexterity,
agility: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].agility,
charisma: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].charisma,
intelligence: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].intelligence
}
},
getCharacterInformation : function() {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getCharacterInformation", ramCost);
}
updateDynamicRam("getCharacterInformation", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].companyPosition instanceof _Company_js__WEBPACK_IMPORTED_MODULE_5__["CompanyPosition"]) {
companyPositionTitle = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.positionName;
}
return {
bitnode: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN,
company: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].companyName,
jobTitle: companyPositionTitle,
city: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].city,
factions: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].factions.slice(),
tor: _SpecialServerIps_js__WEBPACK_IMPORTED_MODULE_20__["SpecialServerIps"].hasOwnProperty("Darkweb Server"),
timeWorked: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].timeWorked,
workHackExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workHackExpGained,
workStrExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workStrExpGained,
workDefExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workDefExpGained,
workDexExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workDexExpGained,
workAgiExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workAgiExpGained,
workChaExpGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workChaExpGained,
workRepGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workRepGained,
workMoneyGain: _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].workMoneyGained,
};
},
isBusy : function() {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 4;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("isBusy", ramCost);
}
updateDynamicRam("isBusy", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].isWorking;
},
stopAction : function() {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn1RamCost / 2;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("stopAction", ramCost);
}
updateDynamicRam("stopAction", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("upgradeHomeRam", ramCost);
}
updateDynamicRam("upgradeHomeRam", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
const cost = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getUpgradeHomeRamCost();
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].getHomeComputer();
homeComputer.maxRam *= 2;
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].loseMoney(cost);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getUpgradeHomeRamCost", ramCost);
}
updateDynamicRam("getUpgradeHomeRamCost", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].getUpgradeHomeRamCost();
},
workForCompany : function() {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("workForCompany", ramCost);
}
updateDynamicRam("workForCompany", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: workForCompany() failed because you are in the middle of a mission.");
return;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition == "" || !(_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
workerScript.scriptRef.log(txt);
}
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].companyPosition.isPartTimeJob()) {
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].startWorkPartTime();
} else {
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].startWork();
}
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForCompany == null) {
workerScript.scriptRef.log("Began working at " + _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].companyName + " as a " + _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("applyToCompany", ramCost);
}
updateDynamicRam("applyToCompany", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].location = companyName;
var res;
switch (field.toLowerCase()) {
case "software":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSoftwareJob(true);
break;
case "software consultant":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSoftwareConsultantJob(true);
break;
case "it":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForItJob(true);
break;
case "security engineer":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSecurityEngineerJob(true);
break;
case "network engineer":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForNetworkEngineerJob(true);
break;
case "business":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForBusinessJob(true);
break;
case "business consultant":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForBusinessConsultantJob(true);
break;
case "security":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForSecurityJob(true);
break;
case "agent":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForAgentJob(true);
break;
case "employee":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForEmployeeJob(true);
break;
case "part-time employee":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForPartTimeEmployeeJob(true);
break;
case "waiter":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].applyForWaiterJob(true);
break;
case "part-time waiter":
res = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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__WEBPACK_IMPORTED_MODULE_32__["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_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getCompanyRep", ramCost);
}
updateDynamicRam("getCompanyRep", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getCompanyFavor", ramCost);
}
updateDynamicRam("getCompanyFavor", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("checkFactionInvitations", ramCost);
}
updateDynamicRam("checkFactionInvitations", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].factionInvitations.slice();
},
joinFaction : function(name) {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("joinFaction", ramCost);
}
updateDynamicRam("joinFaction", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_11__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist.");
return false;
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["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_16__["Player"].factionInvitations.splice(index, 1);
var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_11__["Factions"][name];
Object(_Faction_js__WEBPACK_IMPORTED_MODULE_11__["joinFaction"])(fac);
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("workForFaction", ramCost);
}
updateDynamicRam("workForFaction", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
// if the player is in a gang and the target faction is any of the gang faction, fail
if(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].inGang() && _Gang_js__WEBPACK_IMPORTED_MODULE_10__["AllGangs"][name] !== undefined) {
workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not offer work at the moment.");
return;
}
if (_Missions_js__WEBPACK_IMPORTED_MODULE_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: workForFaction() failed because you are in the middle of a mission.");
return;
}
if (!Object(_Faction_js__WEBPACK_IMPORTED_MODULE_11__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist.");
return false;
}
if (!_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.workForFaction == null) {
workerScript.scriptRef.log(txt);
}
}
var fac = _Faction_js__WEBPACK_IMPORTED_MODULE_11__["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_16__["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_16__["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_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getFactionRep", ramCost);
}
updateDynamicRam("getFactionRep", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_11__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist.");
return -1;
}
return _Faction_js__WEBPACK_IMPORTED_MODULE_11__["Factions"][name].playerReputation;
},
getFactionFavor : function(name) {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn2RamCost;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getFactionFavor", ramCost);
}
updateDynamicRam("getFactionFavor", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_11__["factionExists"])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionFavor() does not exist.");
return -1;
}
return _Faction_js__WEBPACK_IMPORTED_MODULE_11__["Factions"][name].favor;
},
createProgram : function(name) {
var ramCost = _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptSingularityFn3RamCost;
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("createProgram", ramCost);
}
updateDynamicRam("createProgram", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: createProgram() failed because you are in the middle of a mission.");
return;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].singularityStopWork();
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {
workerScript.scriptRef.log(txt);
}
}
name = name.toLowerCase();
let p = null;
for (const key in _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"]) {
if(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"][key].name.toLowerCase() == name) {
p = _CreateProgram_js__WEBPACK_IMPORTED_MODULE_7__["Programs"][key];
}
}
if (p == null) {
workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name);
return false;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].hasProgram(p.name)) {
workerScript.scriptRef.log('ERROR: createProgram() failed because you already have the ' + p.name + ' program');
return false;
}
if (!p.create.req()) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create " + p.name + " (level " + p.create.level + " req)");
return false
}
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].startCreateProgramWork(p.name, p.create.time, p.create.level);
if (workerScript.disableLogs.ALL == null && workerScript.disableLogs.createProgram == null) {
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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("commitCrime", ramCost);
}
updateDynamicRam("commitCrime", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_15__["inMission"]) {
workerScript.scriptRef.log("ERROR: commitCrime() failed because you are in the middle of a mission.");
return;
}
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].isWorking) {
var txt = _Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].city) {
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Aevum:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].AevumSlums;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Chongqing:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].ChongqingSlums;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Sector12Slums;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyo:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].NewTokyoSlums;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Ishima:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].IshimaSlums;
break;
case _Location_js__WEBPACK_IMPORTED_MODULE_13__["Locations"].Volhaven:
_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].location = _Location_js__WEBPACK_IMPORTED_MODULE_13__["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_25__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getCrimeChance", ramCost);
}
updateDynamicRam("getCrimeChance", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_25__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getOwnedAugmentations", ramCost);
}
updateDynamicRam("getOwnedAugmentations", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].augmentations.length; ++i) {
res.push(_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].augmentations[i].name);
}
if (purchased) {
for (var i = 0; i < _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].queuedAugmentations.length; ++i) {
res.push(_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getAugmentationsFromFaction", ramCost);
}
updateDynamicRam("getAugmentationsFromFaction", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_11__["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_11__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("getAugmentationCost", ramCost);
}
updateDynamicRam("getAugmentationCost", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("purchaseAugmentation", ramCost);
}
updateDynamicRam("purchaseAugmentation", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_11__["Factions"][faction];
if (fac == null || !(fac instanceof _Faction_js__WEBPACK_IMPORTED_MODULE_11__["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_16__["Player"].queuedAugmentations.length; ++j) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].augmentations.length; ++j) {
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_11__["purchaseAugmentation"])(aug, fac, true);
workerScript.scriptRef.log(res);
if (Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_32__["isString"])(res) && res.startsWith("You purchased")) {
_Player_js__WEBPACK_IMPORTED_MODULE_16__["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_16__["Player"].bitNodeN !== 4) {ramCost *= 8;}
if (workerScript.checkingRam) {
return updateStaticRam("installAugmentations", ramCost);
}
updateDynamicRam("installAugmentations", ramCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["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_16__["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_16__["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 : {
getContractNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getContractNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getContractNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getContractNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getContractNames() 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");
},
getOperationNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getOperationNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getOperationNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getOperationNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getOperationNames() 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");
},
getBlackOpNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getBlackOpNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getBlackOpNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getBlackOpNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getBlackOpNames() 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");
},
getGeneralActionNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getGeneralActionNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getGeneralActionNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getGeneralActionNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getGeneralActionNames() 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");
},
getSkillNames : function() {
if (workerScript.checkingRam) {
return updateStaticRam("getSkillNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
}
updateDynamicRam("getSkillNames", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 10);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getSkillNamesNetscriptFn();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillNames() 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 (workerScript.checkingRam) {
return updateStaticRam("startAction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("startAction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.startActionNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.startAction() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "startAction() 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");
},
stopBladeburnerAction : function() {
if (workerScript.checkingRam) {
return updateStaticRam("stopBladeburnerAction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2);
}
updateDynamicRam("stopBladeburnerAction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost / 2);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.resetAction();
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "stopBladeburnerAction() 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 (workerScript.checkingRam) {
return updateStaticRam("getActionTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionTime", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionTimeNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionTime() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionTime() 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 (workerScript.checkingRam) {
return updateStaticRam("getActionEstimatedSuccessChance", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionEstimatedSuccessChance", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionEstimatedSuccessChanceNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionEstimatedSuccessChance() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionEstimatedSuccessChance() 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 (workerScript.checkingRam) {
return updateStaticRam("getActionCountRemaining", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getActionCountRemaining", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getActionCountRemaining() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getActionCountRemaining() 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 (workerScript.checkingRam) {
return updateStaticRam("getRank", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getRank", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.rank;
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getRank() 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 (workerScript.checkingRam) {
return updateStaticRam("getSkillPoints", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getSkillPoints", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.skillPoints;
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillPoints() 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 (workerScript.checkingRam) {
return updateStaticRam("getSkillLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getSkillLevel", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getSkillLevel() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getSkillLevel() 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 (workerScript.checkingRam) {
return updateStaticRam("upgradeSkill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("upgradeSkill", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.upgradeSkillNetscriptFn(skillName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.upgradeSkill() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "upgradeSkill() 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(type="", name="") {
if (workerScript.checkingRam) {
return updateStaticRam("getTeamSize", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getTeamSize", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getTeamSize() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getTeamSize() 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 (workerScript.checkingRam) {
return updateStaticRam("setTeamSize", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("setTeamSize", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.setTeamSize() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "setTeamSize() 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 (workerScript.checkingRam) {
return updateStaticRam("getCityEstimatedPopulation", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityEstimatedPopulation", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityEstimatedPopulationNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityEstimatedPopulation() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityEstimatedPopulation() 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 (workerScript.checkingRam) {
return updateStaticRam("getCityEstimatedCommunities", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityEstimatedCommunities", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityEstimatedCommunitiesNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityEstimatedCommunities() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityEstimatedCommunities() 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 (workerScript.checkingRam) {
return updateStaticRam("getCityChaos", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getCityChaos", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.getCityChaosNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.getCityChaos() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getCityChaos() 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 (workerScript.checkingRam) {
return updateStaticRam("switchCity", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("switchCity", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
try {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.switchCityNetscriptFn(cityName, workerScript);
} catch(e) {
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "Bladeburner.switchCity() failed with exception: " + e);
}
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "switchCity() 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 (workerScript.checkingRam) {
return updateStaticRam("getStamina", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("getStamina", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return [_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.stamina, _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.maxStamina];
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "getStamina() 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");
},
joinBladeburnerFaction : function() {
if (workerScript.checkingRam) {
return updateStaticRam("joinBladeburnerFaction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
}
updateDynamicRam("joinBladeburnerFaction", _Constants_js__WEBPACK_IMPORTED_MODULE_6__["CONSTANTS"].ScriptBladeburnerApiBaseRamCost);
if (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner instanceof _Bladeburner_js__WEBPACK_IMPORTED_MODULE_4__["Bladeburner"] && (_Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bitNodeN === 7 || hasBladeburner2079SF)) {
return _Player_js__WEBPACK_IMPORTED_MODULE_16__["Player"].bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);
}
throw Object(_NetscriptEvaluator_js__WEBPACK_IMPORTED_MODULE_25__["makeRuntimeRejectMsg"])(workerScript, "joinBladeburnerFaction() 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/Message.js ***!
\************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Messages", function() { return Messages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "checkForMessagesToSend", function() { return checkForMessagesToSend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendMessage", function() { return sendMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "showMessage", function() { return showMessage; });
/* 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 */ 15);
/* harmony import */ var _CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./CreateProgram.js */ 20);
/* harmony import */ var _Missions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Missions.js */ 41);
/* 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 */ 34);
/* harmony import */ var _Server_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Server.js */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 17);
/* 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);
/* Message.js */
function Message(filename="", msg="") {
this.filename = filename;
this.msg = msg;
this.recvd = false;
}
Message.prototype.toJSON = function() {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_toJSON"])("Message", this);
}
Message.fromJSON = function(value) {
return Object(_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Generic_fromJSON"])(Message, value.data);
}
_utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"].constructors.Message = Message;
//Sends message to player, including a pop up
function sendMessage(msg, forced=false) {
console.log("sending message: " + msg.filename);
msg.recvd = true;
if (forced || !_Settings_js__WEBPACK_IMPORTED_MODULE_6__["Settings"].SuppressMessages) {
showMessage(msg);
}
addMessageToServer(msg, "home");
}
function showMessage(msg) {
var txt = "Message received from unknown sender:
" +
"" + msg.msg + "
" +
"This message was saved as " + msg.filename + " onto your home computer.";
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxCreate"])(txt);
}
//Adds a message to a server
function addMessageToServer(msg, serverHostname) {
var server = Object(_Server_js__WEBPACK_IMPORTED_MODULE_5__["GetServerByHostname"])(serverHostname);
if (server == null) {
console.log("WARNING: Did not locate " + serverHostname);
return;
}
for (var i = 0; i < server.messages.length; ++i) {
if (server.messages[i].filename === msg.filename) {
return; //Already exists
}
}
server.messages.push(msg);
}
//Checks if any of the 'timed' messages should be sent
function checkForMessagesToSend() {
var jumper0 = Messages[MessageFilenames.Jumper0];
var jumper1 = Messages[MessageFilenames.Jumper1];
var jumper2 = Messages[MessageFilenames.Jumper2];
var jumper3 = Messages[MessageFilenames.Jumper3];
var jumper4 = Messages[MessageFilenames.Jumper4];
var cybersecTest = Messages[MessageFilenames.CyberSecTest];
var nitesecTest = Messages[MessageFilenames.NiteSecTest];
var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest];
var redpill = Messages[MessageFilenames.RedPill];
var redpillOwned = false;
if (_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["Augmentations"][_Augmentations_js__WEBPACK_IMPORTED_MODULE_0__["AugmentationNames"].TheRedPill].owned) {
redpillOwned = true;
}
if (redpill && redpillOwned && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].sourceFiles.length === 0 && !_RedPill_js__WEBPACK_IMPORTED_MODULE_4__["redPillFlag"] && !_Missions_js__WEBPACK_IMPORTED_MODULE_2__["inMission"]) {
if (!_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
sendMessage(redpill, true);
}
} else if (redpill && redpillOwned) {
//If player has already destroyed a BitNode, message is not forced
if (!_RedPill_js__WEBPACK_IMPORTED_MODULE_4__["redPillFlag"] && !_Missions_js__WEBPACK_IMPORTED_MODULE_2__["inMission"] && !_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_7__["dialogBoxOpened"]) {
sendMessage(redpill);
}
} else if (jumper0 && !jumper0.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 25) {
sendMessage(jumper0);
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].getHomeComputer().programs.push(_CreateProgram_js__WEBPACK_IMPORTED_MODULE_1__["Programs"].Flight.name);
} else if (jumper1 && !jumper1.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 40) {
sendMessage(jumper1);
} else if (cybersecTest && !cybersecTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 50) {
sendMessage(cybersecTest);
} else if (jumper2 && !jumper2.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 175) {
sendMessage(jumper2);
} else if (nitesecTest && !nitesecTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 200) {
sendMessage(nitesecTest);
} else if (jumper3 && !jumper3.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 350) {
sendMessage(jumper3);
} else if (jumper4 && !jumper4.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 490) {
sendMessage(jumper4);
} else if (bitrunnersTest && !bitrunnersTest.recvd && _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill >= 500) {
sendMessage(bitrunnersTest);
}
}
function AddToAllMessages(msg) {
Messages[msg.filename] = msg;
}
let Messages = {}
function loadMessages(saveString) {
Messages = JSON.parse(saveString, _utils_JSONReviver_js__WEBPACK_IMPORTED_MODULE_8__["Reviver"]);
}
let MessageFilenames = {
Jumper0: "j0.msg",
Jumper1: "j1.msg",
Jumper2: "j2.msg",
Jumper3: "j3.msg",
Jumper4: "j4.msg",
CyberSecTest: "csec-test.msg",
NiteSecTest: "nitesec-test.msg",
BitRunnersTest: "19dfj3l1nd.msg",
RedPill: "icarus.msg",
}
function initMessages() {
//Reset
Messages = {};
//jump3R Messages
AddToAllMessages(new Message(MessageFilenames.Jumper0,
"I know you can sense it. I know you're searching for it. " +
"It's why you spend night after " +
"night at your computer.
It's real, I've seen it. And I can " +
"help you find it. But not right now. You're not ready yet.
" +
"Use this program to track your progress
" +
"The fl1ght.exe program was added to your home computer
" +
"-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper1,
"Soon you will be contacted by a hacking group known as CyberSec. " +
"They can help you with your search.
" +
"You should join them, garner their favor, and " +
"exploit them for their Augmentations. But do not trust them. " +
"They are not what they seem. No one is.
" +
"-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper2,
"Do not try to save the world. There is no world to save. If " +
"you want to find the truth, worry only about yourself. Ethics and " +
"morals will get you killed.
Watch out for a hacking group known as NiteSec." +
"
-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper3,
"You must learn to walk before you can run. And you must " +
"run before you can fly. Look for the black hand.
" +
"I.I.I.I
-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper4,
"To find what you are searching for, you must understand the bits. " +
"The bits are all around us. The runners will help you.
" +
"-jump3R"));
//Messages from hacking factions
AddToAllMessages(new Message(MessageFilenames.CyberSecTest,
"We've been watching you. Your skills are very impressive. But you're wasting " +
"your talents. If you join us, you can put your skills to good use and change " +
"the world for the better. If you join us, we can unlock your full potential.
" +
"But first, you must pass our test. Find and hack our server using the Terminal.
" +
"-CyberSec"));
AddToAllMessages(new Message(MessageFilenames.NiteSecTest,
"People say that the corrupted governments and corporations rule the world. " +
"Yes, maybe they do. But do you know who everyone really fears? People " +
"like us. Because they can't hide from us. Because they can't fight shadows " +
"and ideas with bullets.
" +
"Join us, and people will fear you, too.
" +
"Find and hack our hidden server using the Terminal. Then, we will contact you again." +
"
-NiteSec"));
AddToAllMessages(new Message(MessageFilenames.BitRunnersTest,
"We know what you are doing. We know what drives you. We know " +
"what you are looking for.
" +
"We can help you find the answers.
" +
"run4theh111z"));
AddToAllMessages(new Message(MessageFilenames.RedPill,
"@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*%
" +
")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B)
" +
"@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB
" +
"DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
}
/***/ }),
/* 28 */
/*!*****************************************!*\
!*** ./node_modules/jszip/lib/utils.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var support = __webpack_require__(/*! ./support */ 46);
var base64 = __webpack_require__(/*! ./base64 */ 106);
var nodejsUtils = __webpack_require__(/*! ./nodejsUtils */ 62);
var setImmediate = __webpack_require__(/*! core-js/library/fn/set-immediate */ 168);
var external = __webpack_require__(/*! ./external */ 54);
/**
* Convert a string that pass as a "binary string": it should represent a byte
* array but may have > 255 char codes. Be sure to take only the first byte
* and returns the byte array.
* @param {String} str the string to transform.
* @return {Array|Uint8Array} the string in a binary format.
*/
function string2binary(str) {
var result = null;
if (support.uint8array) {
result = new Uint8Array(str.length);
} else {
result = new Array(str.length);
}
return stringToArrayLike(str, result);
}
/**
* Create a new blob with the given content and the given type.
* @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use
* an Uint8Array because the stock browser of android 4 won't accept it (it
* will be silently converted to a string, "[object Uint8Array]").
*
* Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:
* when a large amount of Array is used to create the Blob, the amount of
* memory consumed is nearly 100 times the original data amount.
*
* @param {String} type the mime type of the blob.
* @return {Blob} the created blob.
*/
exports.newBlob = function(part, type) {
exports.checkSupport("blob");
try {
// Blob constructor
return new Blob([part], {
type: type
});
}
catch (e) {
try {
// deprecated, browser only, old way
var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;
var builder = new Builder();
builder.append(part);
return builder.getBlob(type);
}
catch (e) {
// well, fuck ?!
throw new Error("Bug : can't construct the Blob.");
}
}
};
/**
* The identity function.
* @param {Object} input the input.
* @return {Object} the same input.
*/
function identity(input) {
return input;
}
/**
* Fill in an array with a string.
* @param {String} str the string to use.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
*/
function stringToArrayLike(str, array) {
for (var i = 0; i < str.length; ++i) {
array[i] = str.charCodeAt(i) & 0xFF;
}
return array;
}
/**
* An helper for the function arrayLikeToString.
* This contains static informations and functions that
* can be optimized by the browser JIT compiler.
*/
var arrayToStringHelper = {
/**
* Transform an array of int into a string, chunk by chunk.
* See the performances notes on arrayLikeToString.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @param {String} type the type of the array.
* @param {Integer} chunk the chunk size.
* @return {String} the resulting string.
* @throws Error if the chunk is too big for the stack.
*/
stringifyByChunk: function(array, type, chunk) {
var result = [], k = 0, len = array.length;
// shortcut
if (len <= chunk) {
return String.fromCharCode.apply(null, array);
}
while (k < len) {
if (type === "array" || type === "nodebuffer") {
result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
}
else {
result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
}
k += chunk;
}
return result.join("");
},
/**
* Call String.fromCharCode on every item in the array.
* This is the naive implementation, which generate A LOT of intermediate string.
* This should be used when everything else fail.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
stringifyByChar: function(array){
var resultStr = "";
for(var i = 0; i < array.length; i++) {
resultStr += String.fromCharCode(array[i]);
}
return resultStr;
},
applyCanBeUsed : {
/**
* true if the browser accepts to use String.fromCharCode on Uint8Array
*/
uint8array : (function () {
try {
return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;
} catch (e) {
return false;
}
})(),
/**
* true if the browser accepts to use String.fromCharCode on nodejs Buffer.
*/
nodebuffer : (function () {
try {
return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;
} catch (e) {
return false;
}
})()
}
};
/**
* Transform an array-like object to a string.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
function arrayLikeToString(array) {
// Performances notes :
// --------------------
// String.fromCharCode.apply(null, array) is the fastest, see
// see http://jsperf.com/converting-a-uint8array-to-a-string/2
// but the stack is limited (and we can get huge arrays !).
//
// result += String.fromCharCode(array[i]); generate too many strings !
//
// This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
// TODO : we now have workers that split the work. Do we still need that ?
var chunk = 65536,
type = exports.getTypeOf(array),
canUseApply = true;
if (type === "uint8array") {
canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;
} else if (type === "nodebuffer") {
canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;
}
if (canUseApply) {
while (chunk > 1) {
try {
return arrayToStringHelper.stringifyByChunk(array, type, chunk);
} catch (e) {
chunk = Math.floor(chunk / 2);
}
}
}
// no apply or chunk error : slow and painful algorithm
// default browser on android 4.*
return arrayToStringHelper.stringifyByChar(array);
}
exports.applyFromCharCode = arrayLikeToString;
/**
* Copy the data from an array-like to an other array-like.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
*/
function arrayLikeToArrayLike(arrayFrom, arrayTo) {
for (var i = 0; i < arrayFrom.length; i++) {
arrayTo[i] = arrayFrom[i];
}
return arrayTo;
}
// a matrix containing functions to transform everything into everything.
var transform = {};
// string to ?
transform["string"] = {
"string": identity,
"array": function(input) {
return stringToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["string"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return stringToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": function(input) {
return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));
}
};
// array to ?
transform["array"] = {
"string": arrayLikeToString,
"array": identity,
"arraybuffer": function(input) {
return (new Uint8Array(input)).buffer;
},
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodejsUtils.newBufferFrom(input);
}
};
// arraybuffer to ?
transform["arraybuffer"] = {
"string": function(input) {
return arrayLikeToString(new Uint8Array(input));
},
"array": function(input) {
return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
},
"arraybuffer": identity,
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodejsUtils.newBufferFrom(new Uint8Array(input));
}
};
// uint8array to ?
transform["uint8array"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return input.buffer;
},
"uint8array": identity,
"nodebuffer": function(input) {
return nodejsUtils.newBufferFrom(input);
}
};
// nodebuffer to ?
transform["nodebuffer"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["nodebuffer"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return arrayLikeToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": identity
};
/**
* Transform an input into any type.
* The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
* If no output type is specified, the unmodified input will be returned.
* @param {String} outputType the output type.
* @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
* @throws {Error} an Error if the browser doesn't support the requested output type.
*/
exports.transformTo = function(outputType, input) {
if (!input) {
// undefined, null, etc
// an empty string won't harm.
input = "";
}
if (!outputType) {
return input;
}
exports.checkSupport(outputType);
var inputType = exports.getTypeOf(input);
var result = transform[inputType][outputType](input);
return result;
};
/**
* Return the type of the input.
* The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
* @param {Object} input the input to identify.
* @return {String} the (lowercase) type of the input.
*/
exports.getTypeOf = function(input) {
if (typeof input === "string") {
return "string";
}
if (Object.prototype.toString.call(input) === "[object Array]") {
return "array";
}
if (support.nodebuffer && nodejsUtils.isBuffer(input)) {
return "nodebuffer";
}
if (support.uint8array && input instanceof Uint8Array) {
return "uint8array";
}
if (support.arraybuffer && input instanceof ArrayBuffer) {
return "arraybuffer";
}
};
/**
* Throw an exception if the type is not supported.
* @param {String} type the type to check.
* @throws {Error} an Error if the browser doesn't support the requested type.
*/
exports.checkSupport = function(type) {
var supported = support[type.toLowerCase()];
if (!supported) {
throw new Error(type + " is not supported by this platform");
}
};
exports.MAX_VALUE_16BITS = 65535;
exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
/**
* Prettify a string read as binary.
* @param {string} str the string to prettify.
* @return {string} a pretty string.
*/
exports.pretty = function(str) {
var res = '',
code, i;
for (i = 0; i < (str || "").length; i++) {
code = str.charCodeAt(i);
res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
}
return res;
};
/**
* Defer the call of a function.
* @param {Function} callback the function to call asynchronously.
* @param {Array} args the arguments to give to the callback.
*/
exports.delay = function(callback, args, self) {
setImmediate(function () {
callback.apply(self || null, args || []);
});
};
/**
* Extends a prototype with an other, without calling a constructor with
* side effects. Inspired by nodejs' `utils.inherits`
* @param {Function} ctor the constructor to augment
* @param {Function} superCtor the parent constructor to use
*/
exports.inherits = function (ctor, superCtor) {
var Obj = function() {};
Obj.prototype = superCtor.prototype;
ctor.prototype = new Obj();
};
/**
* Merge the objects passed as parameters into a new one.
* @private
* @param {...Object} var_args All objects to merge.
* @return {Object} a new object with the data of the others.
*/
exports.extend = function() {
var result = {}, i, attr;
for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
for (attr in arguments[i]) {
if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
result[attr] = arguments[i][attr];
}
}
}
return result;
};
/**
* Transform arbitrary content into a Promise.
* @param {String} name a name for the content being processed.
* @param {Object} inputData the content to process.
* @param {Boolean} isBinary true if the content is not an unicode string
* @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.
* @param {Boolean} isBase64 true if the string content is encoded with base64.
* @return {Promise} a promise in a format usable by JSZip.
*/
exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {
// if inputData is already a promise, this flatten it.
var promise = external.Promise.resolve(inputData).then(function(data) {
var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);
if (isBlob && typeof FileReader !== "undefined") {
return new external.Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function(e) {
resolve(e.target.result);
};
reader.onerror = function(e) {
reject(e.target.error);
};
reader.readAsArrayBuffer(data);
});
} else {
return data;
}
});
return promise.then(function(data) {
var dataType = exports.getTypeOf(data);
if (!dataType) {
return external.Promise.reject(
new Error("Can't read the data of '" + name + "'. Is it " +
"in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")
);
}
// special case : it's way easier to work with Uint8Array than with ArrayBuffer
if (dataType === "arraybuffer") {
data = exports.transformTo("uint8array", data);
} else if (dataType === "string") {
if (isBase64) {
data = base64.decode(data);
}
else if (isBinary) {
// optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask
if (isOptimizedBinaryString !== true) {
// this is a string, not in a base64 format.
// Be sure that this is a correct "binary string"
data = string2binary(data);
}
}
}
return data;
});
};
/***/ }),
/* 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__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__);
/* 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__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__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" +
Object(_utils_StringHelperFunctions__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__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " +
"a total of $" + Object(_utils_StringHelperFunctions__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__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__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__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. You also paid $" +
Object(_utils_StringHelperFunctions__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__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_10__["formatNumber"])(stock.price, 2) + " per share. After commissions, you gained " +
"a total of $" + Object(_utils_StringHelperFunctions__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__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__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__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 " +
" || (47Long Position: " +
"Shares in the long position will increase " +
"in value if the price of the corresponding stock increases
" +
"
Shares: " + Object(_utils_StringHelperFunctions__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__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__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__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__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 ***!
\**********************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FconfSettings", function() { return FconfSettings; });
/* 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 */ 32);
/* harmony import */ var _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__);
var FconfSettings = {
ENABLE_BASH_HOTKEYS: false,
ENABLE_TIMESTAMPS: false,
}
var FconfComments = {
ENABLE_BASH_HOTKEYS: "Improved Bash emulation mode. Setting this to 1 enables several\n" +
"new Terminal shortcuts and features that more closely resemble\n" +
"a real Bash-style shell. Note that when this mode is enabled,\n" +
"the default browser shortcuts are overriden by the new Bash\n" +
"shortcuts.\n\n" +
"To see a full list of the Terminal shortcuts that this enables, see:\n" +
"http://bitburner.readthedocs.io/en/latest/shortcuts.html",
ENABLE_TIMESTAMPS: "Terminal commands and log entries will be timestamped. The timestamp\n" +
"will have the format: M/D h:m",
}
//Parse Fconf settings from the config text
//Throws an exception if parsing fails
function parseFconfSettings(config) {
var ast = Object(_utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["parse"])(config, {sourceType:"module"});
var queue = [];
queue.push(ast);
while (queue.length != 0) {
var exp = queue.shift();
switch (exp.type) {
case "BlockStatement":
case "Program":
for (var i = 0; i < exp.body.length; ++i) {
if (exp.body[i] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
queue.push(exp.body[i]);
}
}
break;
case "AssignmentExpression":
var setting, value;
if (exp.left != null && exp.left.name != null) {
setting = exp.left.name;
} else {
break;
}
if (exp.right != null && exp.right.raw != null) {
value = exp.right.raw;
} else {
break;
}
parseFconfSetting(setting, value);
break;
default:
break;
}
for (var prop in exp) {
if (exp.hasOwnProperty(prop)) {
if (exp[prop] instanceof _utils_acorn_js__WEBPACK_IMPORTED_MODULE_0__["Node"]) {
queue.push(exp[prop]);
}
}
}
}
}
function parseFconfSetting(setting, value) {
setting = String(setting);
value = String(value);
if (setting == null || value == null || FconfSettings[setting] == null) {
console.log("WARNING: Invalid .fconf setting: " + setting);
return;
}
//Needed to convert entered value to boolean/strings accordingly
switch(setting) {
case "ENABLE_BASH_HOTKEYS":
case "ENABLE_TIMESTAMPS":
var value = value.toLowerCase();
if (value === "1" || value === "true" || value === "y") {
value = true;
} else {
value = false;
}
FconfSettings[setting] = value;
break;
default:
break;
}
return;
}
//Create the .fconf file text from the settings
function createFconf() {
var res = "";
for (var setting in FconfSettings) {
if (FconfSettings.hasOwnProperty(setting)) {
//Setting comments (description)
var comment = FconfComments[setting];
if (comment == null) {continue;}
var comment = comment.split("\n");
for (var i = 0; i < comment.length; ++i) {
res += ("//" + comment[i] + "\n");
}
var value = 0;
if (FconfSettings[setting] === true) {
value = "1";
} else if (FconfSettings[setting] === false) {
value = "0";
} else {
value = String(FconfSettings[setting]);
}
res += (setting + "=" + value + "\n\n");
}
}
return res;
}
function loadFconf(saveString) {
let tempFconfSettings = JSON.parse(saveString);
for (var setting in tempFconfSettings) {
if (tempFconfSettings.hasOwnProperty(setting)) {
FconfSettings[setting] = tempFconfSettings[setting];
}
}
}
/***/ }),
/* 31 */
/*!***********************************!*\
!*** ./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 */ 13);
/* 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 */ 82);
/* 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 */ 11);
/* harmony import */ var _Settings_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Settings.js */ 17);
/* 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 */ 14);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_11__);
var Promise = __webpack_require__(/*! bluebird */ 183);
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__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__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 "VariableDeclaration":
return evalVariableDeclaration(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 && exp.operator === "||") {
return Promise.resolve(expLeft);
}
if (!expLeft && exp.operator === "&&") {
return Promise.resolve(expLeft);
}
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
" +
"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),
}
/***/ }),
/* 86 */
/*!***********************************************************!*\
!*** ./node_modules/jszip/lib/reader/Uint8ArrayReader.js ***!
\***********************************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var ArrayReader = __webpack_require__(/*! ./ArrayReader */ 88);
var utils = __webpack_require__(/*! ../utils */ 28);
function Uint8ArrayReader(data) {
ArrayReader.call(this, data);
}
utils.inherits(Uint8ArrayReader, ArrayReader);
/**
* @see DataReader.readData
*/
Uint8ArrayReader.prototype.readData = function(size) {
this.checkOffset(size);
if(size === 0) {
// in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
return new Uint8Array(0);
}
var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);
this.index += size;
return result;
};
module.exports = Uint8ArrayReader;
/***/ }),
/* 87 */
/*!*****************************************************!*\
!*** ./node_modules/jszip/lib/reader/DataReader.js ***!
\*****************************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ 28);
function DataReader(data) {
this.data = data; // type : see implementation
this.length = data.length;
this.index = 0;
this.zero = 0;
}
DataReader.prototype = {
/**
* Check that the offset will not go too far.
* @param {string} offset the additional offset to check.
* @throws {Error} an Error if the offset is out of bounds.
*/
checkOffset: function(offset) {
this.checkIndex(this.index + offset);
},
/**
* Check that the specified index will not be too far.
* @param {string} newIndex the index to check.
* @throws {Error} an Error if the index is out of bounds.
*/
checkIndex: function(newIndex) {
if (this.length < this.zero + newIndex || newIndex < 0) {
throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
}
},
/**
* Change the index.
* @param {number} newIndex The new index.
* @throws {Error} if the new index is out of the data.
*/
setIndex: function(newIndex) {
this.checkIndex(newIndex);
this.index = newIndex;
},
/**
* Skip the next n bytes.
* @param {number} n the number of bytes to skip.
* @throws {Error} if the new index is out of the data.
*/
skip: function(n) {
this.setIndex(this.index + n);
},
/**
* Get the byte at the specified index.
* @param {number} i the index to use.
* @return {number} a byte.
*/
byteAt: function(i) {
// see implementations
},
/**
* Get the next number with a given byte size.
* @param {number} size the number of bytes to read.
* @return {number} the corresponding number.
*/
readInt: function(size) {
var result = 0,
i;
this.checkOffset(size);
for (i = this.index + size - 1; i >= this.index; i--) {
result = (result << 8) + this.byteAt(i);
}
this.index += size;
return result;
},
/**
* Get the next string with a given byte size.
* @param {number} size the number of bytes to read.
* @return {string} the corresponding string.
*/
readString: function(size) {
return utils.transformTo("string", this.readData(size));
},
/**
* Get raw data without conversion,
" +
"You gained:
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
return;
}
var facValue = totalValue * _src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
_src_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
var moneyValue = totalValue * _src_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue * _src_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
infiltrationSetText("You can sell the classified documents and secrets " +
"you stole from " + inst.companyName + " for $" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(moneyValue, 2) + " on the black market or you can give it " +
"to a faction to gain " + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with " +
"that faction.");
var selector = document.getElementById("infiltration-faction-select");
selector.innerHTML = "";
for (var i = 0; i < _src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].factions.length; ++i) {
if (_src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].factions[i] === "Bladeburners") {continue;}
selector.innerHTML += "";
}
var sellButton = Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-sell");
setTimeout(function() {
sellButton.addEventListener("click", function() {
_src_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].gainMoney(moneyValue);
Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You sold the classified information you stole from " + inst.companyName +
" for $" + moneyValue + " on the black market!
" +
"You gained:
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
infiltrationBoxClose();
return false;
});
}, 750);
var factionButton = Object(_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-box-faction");
setTimeout(function() {
factionButton.addEventListener("click", function() {
var facName = selector.options[selector.selectedIndex].value;
var faction = _src_Faction_js__WEBPACK_IMPORTED_MODULE_2__["Factions"][facName];
if (faction == null) {
Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("Error finding faction. This is a bug please report to developer");
return false;
}
faction.playerReputation += facValue;
Object(_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You gave the classified information you stole from " + inst.companyName +
" to " + facName + " and gained " + Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(facValue, 3) + " reputation with the faction.
" +
"You gained:
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.hackingExpGained, 3) + " hacking exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.strExpGained, 3) + " str exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.defExpGained, 3) + " def exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.dexExpGained, 3) + " dex exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.agiExpGained, 3) + " agi exp
" +
Object(_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_6__["formatNumber"])(inst.chaExpGained, 3) + " cha exp
");
infiltrationBoxClose();
return false;
});
}, 750);
infiltrationBoxOpen();
}
/***/ }),
/* 120 */
/*!*****************************!*\
!*** ./src/Infiltration.js ***!
\*****************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"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 */ 13);
/* 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 */ 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 */ 119);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/StringHelperFunctions */ 2);
/* harmony import */ var _utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__);
/* Infiltration.js
*
* Kill
* Knockout (nonlethal)
* Stealth Knockout (nonlethal)
* Assassinate
*
* Hack Security
* Destroy Security
* Sneak past Security
*
* Pick the locked door
*
* Bribe security
*
* Escape
*/
let InfiltrationScenarios = {
Guards: "You see an armed security guard patrolling the area.",
TechOnly: "The area is equipped with a state-of-the-art security system: cameras, laser tripwires, and sentry turrets.",
TechOrLockedDoor: "The area is equipped with a state-of-the-art security system. There is a locked door on the side of the " +
"room that can be used to bypass security.",
Bots: "You see a few security bots patrolling the area.",
}
function InfiltrationInstance(companyName, startLevel, val, maxClearance, diff) {
this.companyName = companyName;
this.clearanceLevel = 0;
this.maxClearanceLevel = maxClearance;
this.securityLevel = startLevel;
this.difficulty = diff; //Affects how much security level increases. Represents a percentage
this.baseValue = val; //Base value of company secrets
this.secretsStolen = []; //Numbers representing value of stolen secrets
this.hackingExpGained = 0;
this.strExpGained = 0;
this.defExpGained = 0;
this.dexExpGained = 0;
this.agiExpGained = 0;
this.chaExpGained = 0;
this.intExpGained = 0;
}
InfiltrationInstance.prototype.gainHackingExp = function(amt) {
if (isNaN(amt)) {return;}
this.hackingExpGained += amt;
}
InfiltrationInstance.prototype.gainStrengthExp = function(amt) {
if (isNaN(amt)) {return;}
this.strExpGained += amt;
}
InfiltrationInstance.prototype.gainDefenseExp = function(amt) {
if (isNaN(amt)) {return;}
this.defExpGained += amt;
}
InfiltrationInstance.prototype.gainDexterityExp = function(amt) {
if (isNaN(amt)) {return;}
this.dexExpGained += amt;
}
InfiltrationInstance.prototype.gainAgilityExp = function(amt) {
if (isNaN(amt)) {return;}
this.agiExpGained += amt;
}
InfiltrationInstance.prototype.gainCharismaExp = function(amt) {
if (isNaN(amt)) {return;}
this.chaExpGained += amt;
}
InfiltrationInstance.prototype.gainIntelligenceExp = function(amt) {
if (isNaN(amt)) {return;}
this.intExpGained += amt;
}
function beginInfiltration(companyName, startLevel, val, maxClearance, diff) {
var inst = new InfiltrationInstance(companyName, startLevel, val, maxClearance, diff);
clearInfiltrationStatusText();
nextInfiltrationLevel(inst);
}
function endInfiltration(inst, success) {
if (success) {Object(_utils_InfiltrationBox_js__WEBPACK_IMPORTED_MODULE_6__["infiltrationBoxCreate"])(inst);}
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
_engine_js__WEBPACK_IMPORTED_MODULE_2__["Engine"].loadWorldContent();
}
function nextInfiltrationLevel(inst) {
++inst.clearanceLevel;
updateInfiltrationLevelText(inst);
//Buttons
var killButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-kill");
var knockoutButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-knockout");
var stealthKnockoutButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-stealthknockout");
var assassinateButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-assassinate");
var hackSecurityButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-hacksecurity");
var destroySecurityButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-destroysecurity");
var sneakButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-sneak");
var pickdoorButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-pickdoor");
var bribeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-bribe");
var escapeButton = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["clearEventListeners"])("infiltration-escape");
killButton.style.display = "none";
knockoutButton.style.display = "none";
stealthKnockoutButton.style.display = "none";
assassinateButton.style.display = "none";
hackSecurityButton.style.display = "none";
destroySecurityButton.style.display = "none";
sneakButton.style.display = "none";
pickdoorButton.style.display = "none";
bribeButton.style.display = "none";
escapeButton.style.display = "none";
var rand = Object(_utils_HelperFunctions_js__WEBPACK_IMPORTED_MODULE_5__["getRandomInt"])(0, 5); //This needs to change if more scenarios are added
var scenario = null;
switch (rand) {
case 1:
scenario = InfiltrationScenarios.TechOnly;
hackSecurityButton.style.display = "block";
destroySecurityButton.style.display = "block";
sneakButton.style.display = "block";
escapeButton.style.display = "block";
break;
case 2:
scenario = InfiltrationScenarios.TechOrLockedDoor;
hackSecurityButton.style.display = "block";
destroySecurityButton.style.display = "block";
sneakButton.style.display = "block";
pickdoorButton.style.display = "block";
escapeButton.style.display = "block";
break;
case 3:
scenario = InfiltrationScenarios.Bots;
killButton.style.display = "block";
killButton.addEventListener("click", function() {
var res = attemptInfiltrationKill(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY killed the security bots! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
"level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to kill the security bots. The bots fight back " +
"and raise the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
assassinateButton.style.display = "block";
assassinateButton.addEventListener("click", function() {
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security bots without being detected!");
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to assassinate the security bots. The bots have not detected " +
"you but are now more alert for an intruder. The facility's security level " +
"has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
hackSecurityButton.style.display = "block";
sneakButton.style.display = "block";
escapeButton.style.display = "block";
break;
default: //0, 4-5
scenario = InfiltrationScenarios.Guards;
killButton.style.display = "block";
killButton.addEventListener("click", function() {
var res = attemptInfiltrationKill(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY killed the security guard! Unfortunately you alerted the " +
"rest of the facility's security. The facility's security " +
"level has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3;
++_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to kill the security guard. The guard fights back " +
"and raises the alarm! You take " + dmgTaken + " damage and " +
"the facility's security level has increased by " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
knockoutButton.style.display = "block";
stealthKnockoutButton.style.display = "block";
assassinateButton.style.display = "block";
assassinateButton.addEventListener("click", function() {
var res = attemptInfiltrationAssassinate(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY assassinated the security guard without being detected!");
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].karma -= 3;
++_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to assassinate the security guard. The guard has not detected " +
"you but is now more alert for an intruder. The facility's security level " +
"has increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
});
sneakButton.style.display = "block";
bribeButton.style.display = "block";
escapeButton.style.display = "block";
break;
}
knockoutButton.addEventListener("click", function() {
var res = attemptInfiltrationKnockout(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard! " +
"Unfortunately you made a lot of noise and alerted other security.");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
stealthKnockoutButton.addEventListener("click", function() {
var res = attemptInfiltrationStealthKnockout(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY knocked out the security guard without making " +
"any noise!");
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense));
writeInfiltrationStatusText("You FAILED to stealthily knockout the security guard. The guard " +
"raises the alarm and fights back! You take " + dmgTaken + " damage and " +
"the facility's security level increases by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(dmgTaken)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
hackSecurityButton.addEventListener("click", function() {
var res = attemptInfiltrationHack(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY hacked and disabled the security system!");
writeInfiltrationStatusText("The facility's security level increased by " + ((res[1]*100) - 100).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to hack the security system. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
destroySecurityButton.addEventListener("click", function() {
var res = attemptInfiltrationDestroySecurity(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY and violently destroy the security system!");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to destroy the security system. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
sneakButton.addEventListener("click", function() {
var res = attemptInfiltrationSneak(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY sneak past the security undetected!");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED and were detected while trying to sneak past security! The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
pickdoorButton.addEventListener("click", function() {
var res = attemptInfiltrationPickLockedDoor(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY pick the locked door!");
writeInfiltrationStatusText("The facility's security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to pick the locked door. The facility's security level " +
"increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
bribeButton.addEventListener("click", function() {
var bribeAmt = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationBribeBaseAmount * inst.clearanceLevel;
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].money.lt(bribeAmt)) {
writeInfiltrationStatusText("You do not have enough money to bribe the guard. " +
"You need $" + bribeAmt);
return false;
}
var res = attemptInfiltrationBribe(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY bribed a guard to let you through " +
"to the next clearance level for $" + bribeAmt);
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].loseMoney(bribeAmt);
endInfiltrationLevel(inst);
return false;
} else {
writeInfiltrationStatusText("You FAILED to bribe a guard! The guard is alerting " +
"other security guards about your presence! The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
escapeButton.addEventListener("click", function() {
var res = attemptInfiltrationEscape(inst);
if (res[0]) {
writeInfiltrationStatusText("You SUCCESSFULLY escape from the facility with the stolen classified " +
"documents and company secrets!");
endInfiltration(inst, true);
return false;
} else {
writeInfiltrationStatusText("You FAILED to escape from the facility. You took 1 damage. The facility's " +
"security level increased by " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])((res[1]*100)-100, 2).toString() + "%");
if (_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].takeDamage(1)) {
endInfiltration(inst, false);
}
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
updateInfiltrationButtons(inst, scenario);
writeInfiltrationStatusText("");
writeInfiltrationStatusText("You are now on clearance level " + inst.clearanceLevel + ".
" +
scenario);
}
function endInfiltrationLevel(inst) {
//Check if you gained any secrets
if (inst.clearanceLevel % 5 == 0) {
var baseSecretValue = inst.baseValue * inst.clearanceLevel / 2;
var secretValue = baseSecretValue * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep;
var secretMoneyValue = baseSecretValue * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
inst.secretsStolen.push(baseSecretValue);
Object(_utils_DialogBox_js__WEBPACK_IMPORTED_MODULE_4__["dialogBoxCreate"])("You found and stole a set of classified documents from the company. " +
"These classified secrets could probably be sold for money ($" +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretMoneyValue, 2) + "), or they " +
"could be given to factions for reputation (" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(secretValue, 3) + " rep)");
}
//Increase security level based on difficulty
inst.securityLevel *= (1 + (inst.difficulty / 100));
writeInfiltrationStatusText("You move on to the facility's next clearance level. This " +
"clearance level has " + inst.difficulty + "% higher security");
//If this is max level, force endInfiltration
if (inst.clearanceLevel >= inst.maxClearanceLevel) {
endInfiltration(inst, true);
} else {
nextInfiltrationLevel(inst);
}
}
function writeInfiltrationStatusText(txt) {
var statusTxt = document.getElementById("infiltration-status-text");
statusTxt.innerHTML += (txt + "
");
statusTxt.parentElement.scrollTop = statusTxt.scrollHeight;
}
function clearInfiltrationStatusText() {
document.getElementById("infiltration-status-text").innerHTML = "";
}
function updateInfiltrationLevelText(inst) {
var totalValue = 0;
var totalMoneyValue = 0;
for (var i = 0; i < inst.secretsStolen.length; ++i) {
totalValue += (inst.secretsStolen[i] * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].faction_rep_mult *
_Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationRepValue * _BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationRep);
totalMoneyValue += inst.secretsStolen[i] * _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].InfiltrationMoneyValue *
_BitNode_js__WEBPACK_IMPORTED_MODULE_0__["BitNodeMultipliers"].InfiltrationMoney;
}
var expMultiplier = 2 * inst.clearanceLevel / inst.maxClearanceLevel;
document.getElementById("infiltration-level-text").innerHTML =
"Facility name: " + inst.companyName + "
" +
"Clearance Level: " + inst.clearanceLevel + "
" +
"Security Level: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.securityLevel, 3) + "
" +
"Total reputation value of secrets stolen: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalValue, 3) + "
" +
"Total monetary value of secrets stolen: $" + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(totalMoneyValue, 2) + "
" +
"Hack exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.hackingExpGained * expMultiplier, 3) + "
" +
"Str exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.strExpGained * expMultiplier, 3) + "
" +
"Def exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.defExpGained * expMultiplier, 3) + "
" +
"Dex exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.dexExpGained * expMultiplier, 3) + "
" +
"Agi exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.agiExpGained * expMultiplier, 3) + "
" +
"Cha exp gained: " + Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(inst.chaExpGained * expMultiplier, 3);
}
function updateInfiltrationButtons(inst, scenario) {
var killChance = getInfiltrationKillChance(inst);
var knockoutChance = getInfiltrationKnockoutChance(inst);
var stealthKnockoutChance = getInfiltrationStealthKnockoutChance(inst);
var assassinateChance = getInfiltrationAssassinateChance(inst);
var destroySecurityChance = getInfiltrationDestroySecurityChance(inst);
var hackChance = getInfiltrationHackChance(inst);
var sneakChance = getInfiltrationSneakChance(inst);
var lockpickChance = getInfiltrationPickLockedDoorChance(inst);
var bribeChance = getInfiltrationBribeChance(inst);
var escapeChance = getInfiltrationEscapeChance(inst);
document.getElementById("infiltration-escape").innerHTML = "Escape" +
"" +
"Attempt to escape the facility with the classified secrets and " +
"documents you have stolen. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(escapeChance*100, 2) + "% chance of success. If you fail, " +
"the security level will increase by 5%.";
switch(scenario) {
case InfiltrationScenarios.TechOrLockedDoor:
document.getElementById("infiltration-pickdoor").innerHTML = "Lockpick" +
"" +
"Attempt to pick the locked door. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(lockpickChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increased by 1%. If you fail, the " +
"security level will increase by 3%.";
case InfiltrationScenarios.TechOnly:
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack" +
"" +
"Attempt to hack and disable the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, " +
"the security level will increase by 5%.";
document.getElementById("infiltration-destroysecurity").innerHTML = "Destroy security" +
"" +
"Attempt to violently destroy the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(destroySecurityChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, the " +
"security level will increase by 10%. ";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"" +
"Attempt to sneak past the security system. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. ";
break;
case InfiltrationScenarios.Bots:
document.getElementById("infiltration-kill").innerHTML = "Destroy bots" +
"" +
"Attempt to destroy the security bots through combat. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(killChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, " +
"the security level will increase by 10%. ";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate bots" +
"" +
"Attempt to stealthily destroy the security bots through assassination. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. ";
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack bots" +
"" +
"Attempt to disable the security bots by hacking them. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, " +
"the security level will increase by 5%. ";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"" +
"Attempt to sneak past the security bots. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. ";
break;
case InfiltrationScenarios.Guards:
default:
document.getElementById("infiltration-kill").innerHTML = "Kill" +
"" +
"Attempt to kill the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(killChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 5%. If you fail, " +
"the security level will decrease by 10%. ";
document.getElementById("infiltration-knockout").innerHTML = "Knockout" +
"" +
"Attempt to knockout the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(knockoutChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 3%. If you fail, the " +
"security level will increase by 10%. ";
document.getElementById("infiltration-stealthknockout").innerHTML = "Stealth Knockout" +
"" +
"Attempt to stealthily knockout the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(stealthKnockoutChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. ";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate" +
"" +
"Attempt to assassinate the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 5%. ";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"" +
"Attempt to sneak past the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. ";
document.getElementById("infiltration-bribe").innerHTML = "Bribe" +
"" +
"Attempt to bribe the security guard. You have a " +
Object(_utils_StringHelperFunctions__WEBPACK_IMPORTED_MODULE_7__["formatNumber"])(bribeChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 15%. ";
break;
}
}
let intWgt = _Constants_js__WEBPACK_IMPORTED_MODULE_1__["CONSTANTS"].IntelligenceInfiltrationWeight;
//Kill
//Success: 5%, Failure 10%, -Karma
function attemptInfiltrationKill(inst) {
var chance = getInfiltrationKillChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationKillChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.45 * lvl));
}
//Knockout
//Success: 3%, Failure: 10%
function attemptInfiltrationKnockout(inst) {
var chance = getInfiltrationKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 70) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 70) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 70) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 70) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
return [true, 1.03];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (1.7 * lvl));
}
//Stealth knockout
//Success: 0%, Failure: 10%
function attemptInfiltrationStealthKnockout(inst) {
var chance = getInfiltrationStealthKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 60) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 60) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationStealthKnockoutChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(0.55 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (3 * lvl));
}
//Assassination
//Success: 0%, Failure: 5%, -Karma
function attemptInfiltrationAssassinate(inst) {
var chance = getInfiltrationAssassinateChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 55) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 55) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationAssassinateChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl));
}
//Destroy security
//Success: 5%, Failure: 10%
function attemptInfiltrationDestroySecurity(inst) {
var chance = getInfiltrationDestroySecurityChance(inst);
inst.gainStrengthExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.05;
return [true, 1.05];
} else {
inst.securityLevel *= 1.1;
return [false, 1.1];
}
}
function getInfiltrationDestroySecurityChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].strength +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility) / (2 * lvl));
}
//Hack security
//Success: 3%, Failure: 5%
function attemptInfiltrationHack(inst) {
var chance = getInfiltrationHackChance(inst);
inst.gainHackingExp(inst.securityLevel / 30) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_exp_mult;
inst.gainIntelligenceExp(inst.securityLevel / 680);
if (Math.random() <= chance) {
inst.securityLevel *= 1.03;
return [true, 1.03];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationHackChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].hacking_skill +
(intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence)) / lvl);
}
//Sneak past security
//Success: 0%, Failure: 8%
function attemptInfiltrationSneak(inst) {
var chance = getInfiltrationSneakChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.08;
return [false, 1.08];
}
}
function getInfiltrationSneakChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
0.5 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / (2 * lvl));
}
//Pick locked door
//Success: 1%, Failure: 3%
function attemptInfiltrationPickLockedDoor(inst) {
var chance = getInfiltrationPickLockedDoorChance(inst);
inst.gainDexterityExp(inst.securityLevel / 25) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
if (Math.random() <= chance) {
inst.securityLevel *= 1.01;
return [true, 1.01];
} else {
inst.securityLevel *= 1.03;
return [false, 1.03];
}
}
function getInfiltrationPickLockedDoorChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl);
}
//Bribe
//Success: 0%, Failure: 15%,
function attemptInfiltrationBribe(inst) {
var chance = getInfiltrationBribeChance(inst);
inst.gainCharismaExp(inst.securityLevel / 8) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.15;
return [false, 1.15];
}
}
function getInfiltrationBribeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].charisma) / lvl);
}
//Escape
//Failure: 5%
function attemptInfiltrationEscape(inst) {
var chance = getInfiltrationEscapeChance(inst);
inst.gainAgilityExp(inst.securityLevel / 30) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 30) * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity_exp_mult;
if (Math.random() <= chance) {
return [true, 1];
} else {
inst.securityLevel *= 1.05;
return [false, 1.05];
}
}
function getInfiltrationEscapeChance(inst) {
var lvl = inst.securityLevel;
return Math.min(0.95,
(2 * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].agility +
_Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].dexterity +
intWgt * _Player_js__WEBPACK_IMPORTED_MODULE_3__["Player"].intelligence) / lvl);
}
/***/ }),
/* 121 */
/*!**********************************************!*\
!*** ./node_modules/file-saver/FileSaver.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.3.2
* 2016-06-16 18:25:19
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs || (function(view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var
doc = view.document
// only get URL when necessary in case Blob.js hasn't overridden it yet
, get_URL = function() {
return view.URL || view.webkitURL || view;
}
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
}
, is_safari = /constructor/i.test(view.HTMLElement) || view.safari
, is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
, throw_outside = function(ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
, arbitrary_revoke_timeout = 1000 * 40 // in ms
, revoke = function(file) {
var revoker = function() {
if (typeof file === "string") { // file is an object URL
get_URL().revokeObjectURL(file);
} else { // file is a File
file.remove();
}
};
setTimeout(revoker, arbitrary_revoke_timeout);
}
, dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, auto_bom = function(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
}
return blob;
}
, FileSaver = function(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, force = type === force_saveable_type
, object_url
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function() {
var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
var popup = view.open(url, '_blank');
if(!popup) view.location.href = url;
url=undefined; // release reference before dispatching
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (!object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (force) {
view.location.href = object_url;
} else {
var opened = view.open(object_url, "_blank");
if (!opened) {
// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
}
;
filesaver.readyState = filesaver.INIT;
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
setTimeout(function() {
save_link.href = object_url;
save_link.download = name;
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
fs_error();
}
, FS_proto = FileSaver.prototype
, saveAs = function(blob, name, no_auto_bom) {
return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
}
;
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function(blob, name, no_auto_bom) {
name = name || blob.name || "download";
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name);
};
}
FS_proto.abort = function(){};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
return saveAs;
}(
typeof self !== "undefined" && self
|| typeof window !== "undefined" && window
|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if (("function" !== "undefined" && __webpack_require__(/*! !webpack amd define */ 81) !== null) && (__webpack_require__(/*! !webpack amd options */ 131) !== null)) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return saveAs;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ }),
/* 122 */
/*!*****************************************!*\
!*** ./node_modules/jszip/lib/index.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Representation a of zip file in js
* @constructor
*/
function JSZip() {
// if this constructor is used without `new`, it adds `new` before itself:
if(!(this instanceof JSZip)) {
return new JSZip();
}
if(arguments.length) {
throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");
}
// object containing the files :
// {
// "folder/" : {...},
// "folder/data.txt" : {...}
// }
this.files = {};
this.comment = null;
// Where we are in the hierarchy
this.root = "";
this.clone = function() {
var newObj = new JSZip();
for (var i in this) {
if (typeof this[i] !== "function") {
newObj[i] = this[i];
}
}
return newObj;
};
}
JSZip.prototype = __webpack_require__(/*! ./object */ 181);
JSZip.prototype.loadAsync = __webpack_require__(/*! ./load */ 136);
JSZip.support = __webpack_require__(/*! ./support */ 46);
JSZip.defaults = __webpack_require__(/*! ./defaults */ 100);
// TODO find a better way to handle this version,
// a require('package.json').version doesn't work with webpack, see #327
JSZip.version = "3.1.5";
JSZip.loadAsync = function (content, options) {
return new JSZip().loadAsync(content, options);
};
JSZip.external = __webpack_require__(/*! ./external */ 54);
module.exports = JSZip;
/***/ }),
/* 123 */,
/* 124 */,
/* 125 */,
/* 126 */,
/* 127 */,
/* 128 */
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/bytesToUuid.js ***!
\**********************************************/
/***/ (function(module, exports) {
/**
* Convert array of 16 byte values to UUID string format of the form:
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
*/
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex[i] = (i + 0x100).toString(16).substr(1);
}
function bytesToUuid(buf, offset) {
var i = offset || 0;
var bth = byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
module.exports = bytesToUuid;
/***/ }),
/* 129 */
/*!**********************************************!*\
!*** ./node_modules/uuid/lib/rng-browser.js ***!
\**********************************************/
/***/ (function(module, exports) {
// Unique ID creation requires a high quality random # generator. In the
// browser this is a little complicated due to unknown quality of Math.random()
// and inconsistent support for the `crypto` API. We do the best we can via
// feature-detection
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) ||
(typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto));
if (getRandomValues) {
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
module.exports = function whatwgRNG() {
getRandomValues(rnds8);
return rnds8;
};
} else {
// Math.random()-based (RNG)
//
// If all else fails, use Math.random(). It's fast, but is of unspecified
// quality.
var rnds = new Array(16);
module.exports = function mathRNG() {
for (var i = 0, r; i < 16; i++) {
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
}
return rnds;
};
}
/***/ }),
/* 130 */
/*!************************************!*\
!*** ./src/NetscriptJSPreamble.js ***!
\************************************/
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEnv", function() { return registerEnv; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "unregisterEnv", function() { return unregisterEnv; });
/* 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 */ 117);
/* 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 */ 116);
/* 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
// variables appropriately for the module.
//
// One caveat is that we don't allow the variables in the preable
// to change. Unlike in normal Javascript, this would not change
// properties of self. It would instead just change the variable
// within the given module -- not good! Users should not really
// need to do this anyway.
window.__NSJS__environments = {};
// Returns the UUID for the env.
function registerEnv(env) {
const uuid = uuid_v4__WEBPACK_IMPORTED_MODULE_0___default()();
window.__NSJS__environments[uuid] = env;
return uuid;
}
function unregisterEnv(uuid) {
delete window.__NSJS__environments[uuid];
}
function makeEnvHeader(uuid) {
if (!(uuid in window.__NSJS__environments)) throw new Error("uuid is not in the environment" + uuid);
const env = window.__NSJS__environments[uuid];
var envLines = [];
for (const prop in env) {
envLines.push("const ", prop, " = ", "__NSJS_ENV[\"", prop, "\"];\n");
}
return Object(sprintf_js__WEBPACK_IMPORTED_MODULE_1__["sprintf"])(`
'use strict';
const __NSJS_ENV = window.__NSJS__environments['%s'];
// The global variable assignments (hack, weaken, etc.).
%s
`, uuid, envLines.join(""));
}
/***/ }),
/* 131 */
/*!****************************************!*\
!*** (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, {}))
/***/ }),
/* 132 */
/*!********************************************!*\
!*** ./node_modules/jszip/lib/zipEntry.js ***!
\********************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var readerFor = __webpack_require__(/*! ./reader/readerFor */ 89);
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 */ 96);
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;
/***/ }),
/* 133 */
/*!***********************************************************!*\
!*** ./node_modules/jszip/lib/reader/NodeBufferReader.js ***!
\***********************************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Uint8ArrayReader = __webpack_require__(/*! ./Uint8ArrayReader */ 86);
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;
/***/ }),
/* 134 */
/*!*******************************************************!*\
!*** ./node_modules/jszip/lib/reader/StringReader.js ***!
\*******************************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var DataReader = __webpack_require__(/*! ./DataReader */ 87);
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;
/***/ }),
/* 135 */
/*!**********************************************!*\
!*** ./node_modules/jszip/lib/zipEntries.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var readerFor = __webpack_require__(/*! ./reader/readerFor */ 89);
var utils = __webpack_require__(/*! ./utils */ 28);
var sig = __webpack_require__(/*! ./signature */ 90);
var ZipEntry = __webpack_require__(/*! ./zipEntry */ 132);
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;
/***/ }),
/* 136 */
/*!****************************************!*\
!*** ./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 */ 135);
var Crc32Probe = __webpack_require__(/*! ./stream/Crc32Probe */ 97);
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;
});
};
/***/ }),
/* 137 */
/*!*******************************************************************!*\
!*** ./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 */ 36);
/**
* 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;
/***/ }),
/* 138 */
/*!**********************************************************!*\
!*** ./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 */ 36);
var utf8 = __webpack_require__(/*! ../utf8 */ 52);
var crc32 = __webpack_require__(/*! ../crc32 */ 72);
var signature = __webpack_require__(/*! ../signature */ 90);
/**
* 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;
/***/ }),
/* 139 */
/*!************************************************!*\
!*** ./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;
/***/ }),
/* 140 */
/*!************************************************!*\
!*** ./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;
};
/***/ }),
/* 141 */
/*!***********************************************!*\
!*** ./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;
};
/***/ }),
/* 142 */
/*!***********************************************!*\
!*** ./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 */ 95);
var crc32 = __webpack_require__(/*! ./crc32 */ 94);
var inflate_fast = __webpack_require__(/*! ./inffast */ 141);
var inflate_table = __webpack_require__(/*! ./inftrees */ 140);
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;
*/
/***/ }),
/* 143 */
/*!******************************************!*\
!*** ./node_modules/pako/lib/inflate.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var zlib_inflate = __webpack_require__(/*! ./zlib/inflate */ 142);
var utils = __webpack_require__(/*! ./utils/common */ 45);
var strings = __webpack_require__(/*! ./utils/strings */ 93);
var c = __webpack_require__(/*! ./zlib/constants */ 91);
var msg = __webpack_require__(/*! ./zlib/messages */ 71);
var ZStream = __webpack_require__(/*! ./zlib/zstream */ 92);
var GZheader = __webpack_require__(/*! ./zlib/gzheader */ 139);
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;
/***/ }),
/* 144 */
/*!*********************************************!*\
!*** ./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<