bitburner-src/dist/bundle.js
2017-09-01 15:42:28 -05:00

64356 lines
2.8 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/******/ (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, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // 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 = 4);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Player; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return loadPlayer; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Crimes_js__ = __webpack_require__(40);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Gang_js__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__SourceFile_js__ = __webpack_require__(30);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_13__utils_decimal_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_IPAddress_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__ = __webpack_require__(5);
function PlayerObject() {
//Skills and stats
this.hacking_skill = 1;
//Fighting
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;
//Intelligence, perhaps?
//Hacking multipliers
this.hacking_chance_mult = 1; //Increase through ascensions/augmentations
this.hacking_speed_mult = 1; //Decrease through ascensions/augmentations
this.hacking_money_mult = 1; //Increase through ascensions/augmentations. Can't go above 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.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 __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(1000);
this.total_money = new __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(0); //Total money ever earned in this "simulation"
this.lifetime_money = new __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(0); //Total money ever earned
//IP Address of Starting (home) computer
this.homeComputer = "";
//Location information
this.city = __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* 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.discoveredServers = []; //IP addresses of secret servers not in the network that you have discovered
this.purchasedServers = [];
this.hacknetNodes = [];
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.className = "";
this.crimeType = "";
this.timeWorked = 0; //in ms
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;
//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;
};
PlayerObject.prototype.init = function() {
/* Initialize Player's home computer */
var t_homeComp = new __WEBPACK_IMPORTED_MODULE_10__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_16__utils_IPAddress_js__["a" /* createRandomIp */])(), "home", "Home PC", true, true, true, 8);
this.homeComputer = t_homeComp.ip;
this.currentServer = t_homeComp.ip;
Object(__WEBPACK_IMPORTED_MODULE_10__Server_js__["a" /* AddToAllServers */])(t_homeComp);
this.getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].NukeProgram);
}
PlayerObject.prototype.increaseMultiplier = function(name, val) {
let mult = this[name];
if (mult === null || mult === undefined) {
console.log("ERROR: Could not find this multiplier " + name);
return;
}
mult *= val;
}
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 __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(1000);
this.city = __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.discoveredServers = [];
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.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 __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(1000);
this.city = __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12;
this.location = "";
this.companyName = "";
this.companyPosition = "";
this.discoveredServers = [];
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;
//Reset Stock market
this.hasWseAccount = false;
this.hasTixApiAccess = false;
this.playtimeSinceLastAug = 0;
}
PlayerObject.prototype.getCurrentServer = function() {
return __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][this.currentServer];
}
PlayerObject.prototype.getHomeComputer = function() {
return __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][this.homeComputer];
}
//Calculates skill level based on experience. The same formula will be used for every skill
// At the maximum possible exp (MAX_INT = 9007199254740991), the hacking skill will be 1796 TODO REcalculate this
// Gets to level 1000 hacking skill at (TODO Determine this)
PlayerObject.prototype.calculateSkill = function(exp) {
return Math.max(Math.floor(32 * Math.log(exp + 534.5) - 200), 1);
}
PlayerObject.prototype.updateSkillLevels = function() {
this.hacking_skill = Math.floor(this.calculateSkill(this.hacking_exp) * this.hacking_mult);
this.strength = Math.floor(this.calculateSkill(this.strength_exp) * this.strength_mult);
this.defense = Math.floor(this.calculateSkill(this.defense_exp) * this.defense_mult);
this.dexterity = Math.floor(this.calculateSkill(this.dexterity_exp) * this.dexterity_mult);
this.agility = Math.floor(this.calculateSkill(this.agility_exp) * this.agility_mult);
this.charisma = Math.floor(this.calculateSkill(this.charisma_exp) * this.charisma_mult);
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;
}
//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);
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);
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 * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* 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) * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* 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;
}
PlayerObject.prototype.gainStrengthExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainStrengthExp()"); return;
}
this.strength_exp += exp;
}
PlayerObject.prototype.gainDefenseExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into player.gainDefenseExp()"); return;
}
this.defense_exp += exp;
}
PlayerObject.prototype.gainDexterityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainDexterityExp()"); return;
}
this.dexterity_exp += exp;
}
PlayerObject.prototype.gainAgilityExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainAgilityExp()"); return;
}
this.agility_exp += exp;
}
PlayerObject.prototype.gainCharismaExp = function(exp) {
if (isNaN(exp)) {
console.log("ERR: NaN passed into Player.gainCharismaExp()"); return;
}
this.charisma_exp += exp;
}
/******* 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.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 = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
company.playerReputation += (this.workRepGained);
this.gainMoney(this.workMoneyGained);
this.updateSkillLevels();
var txt = "You earned a total of: <br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + "<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " reputation for the company <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp<br>";
if (cancelled) {
txt = "You worked a short shift of " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + " <br><br> " +
"Since you cancelled your work early, you only gained half of the reputation you earned. <br><br>" + txt;
} else {
txt = "You worked a full shift of 8 hours! <br><br> " +
"You earned a total of: <br>" + txt;
}
if (!sing) {Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadTerminalContent();
if (sing) {
return "You worked a short shift of " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + " and " +
"earned $" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + ", " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " reputation, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp, and " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp.";
}
}
PlayerObject.prototype.startWork = function() {
this.resetWorkStatus();
this.isWorking = true;
this.workType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* clearEventListeners */])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Cancel Work";
newCancelButton.addEventListener("click", function() {
Player.finishWork(true);
return false;
});
//Display Work In Progress Screen
__WEBPACK_IMPORTED_MODULE_6__engine_js__["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 / __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed;
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (this.timeWorked >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours) {
var maxCycles = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working as a " + this.companyPosition.positionName +
" at " + Player.companyName + "<br><br>" +
"You have been working for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + " ($" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec) <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp <br><br> " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp <br><br>" +
"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 = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours;
var newCancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* clearEventListeners */])("work-in-progress-cancel-button");
newCancelButton.innerHTML = "Stop Working";
newCancelButton.addEventListener("click", function() {
Player.finishWorkPartTime();
return false;
});
//Display Work In Progress Screen
__WEBPACK_IMPORTED_MODULE_6__engine_js__["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 / __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed;
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 8 hours, then finish. You can only gain 8 hours worth of exp and money
if (this.timeWorked >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours) {
var maxCycles = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 + "<br><br>" +
"You have been working for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + " ($" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec) <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this company <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp <br><br> " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp <br><br>" +
"You will automatically finish after working for 8 hours. You can cancel earlier if you wish, <br>" +
"and there will be no penalty because this is a part-time job.";
}
PlayerObject.prototype.finishWorkPartTime = function(sing=false) {
this.gainWorkExp();
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
company.playerReputation += (this.workRepGained);
this.gainMoney(this.workMoneyGained);
this.updateSkillLevels();
var txt = "You earned a total of: <br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + "<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " reputation for the company <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp<br>";
txt = "You worked for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br> " + txt;
if (!sing) {Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadTerminalContent();
if (sing) {
return "You worked for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + " and " +
"earned a total of " +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + ", " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " reputation, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp, and " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp";
}
}
/* Working for Faction */
PlayerObject.prototype.finishFactionWork = function(cancelled, sing=false) {
this.gainWorkExp();
var faction = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + " <br><br> " +
"You earned a total of: <br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + "<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " reputation for the faction <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp<br>";
if (!sing) {Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadTerminalContent();
if (sing) {
return "You worked for your faction " + faction.name + " for a total of " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + ". " +
"You earned " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " rep, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " str exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " def exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dex exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agi exp, and " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " cha exp.";
}
}
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 *= __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkRepGain;
this.isWorking = true;
this.workType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction;
this.currentWorkFactionName = faction.name;
this.timeNeededToCompleteWork = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer20Hours;
var cancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* 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
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.startFactionHackWork = function(faction) {
this.resetWorkStatus();
this.workHackExpGainRate = .15 * this.hacking_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workRepGainRate = this.hacking_skill / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel * this.faction_rep_mult;
this.factionWorkType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workStrExpGainRate = .1 * this.strength_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workDefExpGainRate = .1 * this.defense_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workDexExpGainRate = .1 * this.dexterity_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workAgiExpGainRate = .1 * this.agility_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workChaExpGainRate = .1 * this.charisma_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workRepGainRate = this.getFactionFieldWorkRepGain();
this.factionWorkType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workStrExpGainRate = 0.15 * this.strength_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workDefExpGainRate = 0.15 * this.defense_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workDexExpGainRate = 0.15 * this.dexterity_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workAgiExpGainRate = 0.15 * this.agility_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workChaExpGainRate = 0.00 * this.charisma_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionWorkExpGain;
this.workRepGainRate = this.getFactionSecurityWorkRepGain();
this.factionWorkType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].FactionWorkSecurity;
this.currentWorkFactionDescription = "performing security detail"
this.startFactionWork(faction);
}
PlayerObject.prototype.workForFaction = function(numCycles) {
var faction = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */][this.currentWorkFactionName];
//Constantly update the rep gain rate
switch (this.factionWorkType) {
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].FactionWorkHacking:
this.workRepGainRate = this.hacking_skill / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel * this.faction_rep_mult;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].FactionWorkField:
this.workRepGainRate = this.getFactionFieldWorkRepGain();
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 *= __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* 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 / __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed;
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed * numCycles;
//If timeWorked == 20 hours, then finish. You can only work for the faction for 20 hours
if (this.timeWorked >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MillisecondsPer20Hours) {
var maxCycles = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].GameCyclesPer20Hours;
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 + "." +
" You have been doing this for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br>" +
"You have earned: <br><br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGainRate * cyclesPerSec, 2) + " / sec) <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workRepGainRate * cyclesPerSec, 4) + " / sec) reputation for this faction <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp <br><br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp <br><br> " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp <br><br>" +
"You will automatically finish after working for 20 hours. You can cancel earlier if you wish.<br>" +
"There is no penalty for cancelling earlier.";
}
//Money gained per game cycle
PlayerObject.prototype.getWorkMoneyGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.baseSalary * company.salaryMultiplier *
this.work_money_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkMoney;
}
//Hack exp gained per game cycle
PlayerObject.prototype.getWorkHackExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.hackingExpGain * company.expMultiplier *
this.hacking_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Str exp gained per game cycle
PlayerObject.prototype.getWorkStrExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.strengthExpGain * company.expMultiplier *
this.strength_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Def exp gained per game cycle
PlayerObject.prototype.getWorkDefExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.defenseExpGain * company.expMultiplier *
this.defense_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Dex exp gained per game cycle
PlayerObject.prototype.getWorkDexExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.dexterityExpGain * company.expMultiplier *
this.dexterity_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Agi exp gained per game cycle
PlayerObject.prototype.getWorkAgiExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.agilityExpGain * company.expMultiplier *
this.agility_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Charisma exp gained per game cycle
PlayerObject.prototype.getWorkChaExpGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
return this.companyPosition.charismaExpGain * company.expMultiplier *
this.charisma_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CompanyWorkExpGain;
}
//Reputation gained per game cycle
PlayerObject.prototype.getWorkRepGain = function() {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
var jobPerformance = this.companyPosition.calculateJobPerformance(this.hacking_skill, this.strength,
this.defense, this.dexterity,
this.agility, this.charisma);
//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 / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.strength / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.defense / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.dexterity / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.agility / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel) / 5;
return t * this.faction_rep_mult;
}
PlayerObject.prototype.getFactionFieldWorkRepGain = function() {
var t = 0.9 * (this.hacking_skill / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.strength / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.defense / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.dexterity / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.agility / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
this.charisma / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel) / 6;
return t * this.faction_rep_mult;
}
/* Creating a Program */
PlayerObject.prototype.startCreateProgramWork = function(programName, time, reqLevel) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 = (__WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel - (this.hacking_skill - reqLevel)) / __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
if (timeMultiplier > 1) {timeMultiplier = 1;}
if (timeMultiplier < 0.01) {timeMultiplier = 0.01;}
this.timeNeededToCompleteWork = timeMultiplier * time;
//Check for incomplete program
for (var i = 0; i < Player.getHomeComputer().programs.length; ++i) {
var programFile = Player.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.timeWorked = percComplete / 100 * this.timeNeededToCompleteWork;
Player.getHomeComputer().programs.splice(i, 1);
}
}
this.createProgramName = programName;
var cancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* 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
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.createProgramWork = function(numCycles) {
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed * numCycles;
var programName = this.createProgramName;
if (this.timeWorked >= this.timeNeededToCompleteWork) {
this.finishCreateProgramWork(false);
}
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You are currently working on coding " + programName + ".<br><br> " +
"You have been working for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br>" +
"The program is " + (this.timeWorked / this.timeNeededToCompleteWork * 100).toFixed(2) + "% complete. <br>" +
"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(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You've finished creating " + programName + "!<br>" +
"The new program can be found on your home computer.");
Player.getHomeComputer().programs.push(programName);
} else {
var perc = Math.floor(this.timeWorked / this.timeNeededToCompleteWork * 100).toString();
var incompleteName = programName + "-" + perc + "%-INC";
Player.getHomeComputer().programs.push(incompleteName);
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
Player.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadTerminalContent();
}
/* Studying/Taking Classes */
PlayerObject.prototype.startClass = function(costMult, expMult, className) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass;
this.className = className;
var gameCPS = 1000 / __WEBPACK_IMPORTED_MODULE_6__engine_js__["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 __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassStudyComputerScience:
hackExp = baseStudyComputerScienceExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassDataStructures:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassDataStructuresBaseCost * costMult / gameCPS;
hackExp = baseDataStructuresExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassNetworks:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassNetworksBaseCost * costMult / gameCPS;
hackExp = baseNetworksExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassAlgorithms:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassAlgorithmsBaseCost * costMult / gameCPS;
hackExp = baseAlgorithmsExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassManagement:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassManagementBaseCost * costMult / gameCPS;
chaExp = baseManagementExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassLeadership:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassLeadershipBaseCost * costMult / gameCPS;
chaExp = baseLeadershipExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymStrength:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymBaseCost * costMult / gameCPS;
strExp = baseGymExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymDefense:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymBaseCost * costMult / gameCPS;
defExp = baseGymExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymBaseCost * costMult / gameCPS;
dexExp = baseGymExp * expMult / gameCPS;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymAgility:
cost = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymBaseCost * costMult / gameCPS;
agiExp = baseGymExp * expMult / gameCPS;
break;
default:
throw new Error("ERR: Invalid/unregocnized class name");
return;
}
this.workMoneyLossRate = cost;
this.workHackExpGainRate = hackExp * this.hacking_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;
this.workStrExpGainRate = strExp * this.strength_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;;
this.workDefExpGainRate = defExp * this.defense_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;;
this.workDexExpGainRate = dexExp * this.dexterity_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;;
this.workAgiExpGainRate = agiExp * this.agility_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;;
this.workChaExpGainRate = chaExp * this.charisma_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].ClassGymExpGain;;
var cancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* clearEventListeners */])("work-in-progress-cancel-button");
if (className == __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymStrength ||
className == __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymDefense ||
className == __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity ||
className == __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.takeClass = function(numCycles) {
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["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 / __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed;
var txt = document.getElementById("work-in-progress-text");
txt.innerHTML = "You have been " + className + " for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + "<br><br>" +
"This has cost you: <br>" +
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + " ($" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyLossRate * cyclesPerSec, 2) + " / sec) <br><br>" +
"You have gained: <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGainRate * cyclesPerSec, 4) + " / sec) hacking exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGainRate * cyclesPerSec, 4) + " / sec) defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGainRate * cyclesPerSec, 4) + " / sec) strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGainRate * cyclesPerSec, 4) + " / sec) dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGainRate * cyclesPerSec, 4) + " / sec) agility exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " (" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGainRate * cyclesPerSec, 4) + " / sec) charisma exp <br>" +
"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();
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(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + ", <br>" +
"you spent a total of $" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained * -1, 2) + ". <br><br>" +
"You earned a total of: <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility exp <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma exp<br>";
if (!sing) {Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadLocationContent();
if (sing) {return "After " + this.className + " for " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeWorked) + ", " +
"you spent a total of $" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained * -1, 2) + ". " +
"You earned a total of: " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 3) + " hacking exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 3) + " strength exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 3) + " defense exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 3) + " dexterity exp, " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 3) + " agility exp, and " +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 3) + " charisma exp";}
}
//The EXP and $ gains are hardcoded. Time is in ms
PlayerObject.prototype.startCrime = function(hackExp, strExp, defExp, dexExp, agiExp, chaExp, money, time) {
this.resetWorkStatus();
this.isWorking = true;
this.workType = __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeCrime;
this.workHackExpGained = hackExp * this.hacking_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workStrExpGained = strExp * this.strength_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workDefExpGained = defExp * this.defense_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workDexExpGained = dexExp * this.dexterity_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workAgiExpGained = agiExp * this.agility_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workChaExpGained = chaExp * this.charisma_exp_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeExpGain;
this.workMoneyGained = money * this.crime_money_mult * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].CrimeMoney;
this.timeNeededToCompleteWork = time;
//Remove all old event listeners from Cancel button
var newCancelButton = Object(__WEBPACK_IMPORTED_MODULE_15__utils_HelperFunctions_js__["b" /* clearEventListeners */])("work-in-progress-cancel-button")
newCancelButton.innerHTML = "Cancel crime"
newCancelButton.addEventListener("click", function() {
Player.finishCrime(true);
return false;
});
//Display Work In Progress Screen
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadWorkInProgressContent();
}
PlayerObject.prototype.commitCrime = function (numCycles) {
this.timeWorked += __WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"]._idleSpeed * numCycles;
if (this.timeWorked >= this.timeNeededToCompleteWork) {Player.finishCrime(false); return;}
var percent = Math.round(Player.timeWorked / Player.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 " + Player.crimeType + ".<br>" +
"Time remaining: " + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(this.timeNeededToCompleteWork - this.timeWorked) + "<br>" +
progressBar.replace( / /g, "&nbsp;" );
}
PlayerObject.prototype.finishCrime = function(cancelled) {
//Determine crime success/failure
if (!cancelled) {
var statusText = ""; //TODO, unique message for each crime when you succeed
if (Object(__WEBPACK_IMPORTED_MODULE_5__Crimes_js__["w" /* determineCrimeSuccess */])(this.crimeType, this.workMoneyGained)) {
//Handle Karma and crime statistics
switch(this.crimeType) {
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeShoplift:
this.karma -= 0.1;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeRobStore:
this.karma -= 0.5;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeMug:
this.karma -= 0.25;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeLarceny:
this.karma -= 1.5;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeDrugs:
this.karma -= 0.5;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeTraffickArms:
this.karma -= 1;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeHomicide:
++this.numPeopleKilled;
this.karma -= 3;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeGrandTheftAuto:
this.karma -= 5;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeKidnap:
this.karma -= 6;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeAssassination:
++this.numPeopleKilled;
this.karma -= 10;
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CrimeHeist:
this.karma -= 15;
break;
default:
console.log(this.crimeType);
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERR: Unrecognized crime type. This is probably a bug please contact the developer");
return;
}
//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;
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Crime successful! <br><br>" +
"You gained:<br>"+
"$" + Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workMoneyGained, 2) + "<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking experience <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma experience");
} else {
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Crime failed! <br><br>" +
"You gained:<br>"+
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workHackExpGained, 4) + " hacking experience <br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workStrExpGained, 4) + " strength experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDefExpGained, 4) + " defense experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workDexExpGained, 4) + " dexterity experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workAgiExpGained, 4) + " agility experience<br>" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.workChaExpGained, 4) + " charisma experience");
}
this.gainWorkExp();
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
this.isWorking = false;
__WEBPACK_IMPORTED_MODULE_6__engine_js__["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 __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass:
res = this.finishClass(true);
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeCompany:
res = this.finishWork(true, true);
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeCompanyPartTime:
res = this.finishWorkPartTime(true);
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction:
res = this.finishFactionWork(true, true);
break;
case __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].WorkTypeCreateProgram:
res = this.finishCreateProgramWork(true, 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(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(this.max_hp * __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].HospitalCostPerHp, 2));
Player.loseMoney(this.max_hp * __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
}
var currPositionName = "";
if (this.companyPosition != "") {
currPositionName = this.companyPosition.positionName;
}
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (sing && !(company instanceof __WEBPACK_IMPORTED_MODULE_2__Company_js__["b" /* Company */])) {
return "ERROR: Invalid company name: " + this.location + ". applyToCompany() failed";
}
var pos = entryPosType;
if (!this.isQualified(company, pos)) {
var reqText = Object(__WEBPACK_IMPORTED_MODULE_2__Company_js__["f" /* getJobRequirementText */])(company, pos);
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position<br>" + reqText);
return;
}
while (true) {
if (__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].Debug) {console.log("Determining qualification for next Company Position");}
var newPos = Object(__WEBPACK_IMPORTED_MODULE_2__Company_js__["g" /* 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(__WEBPACK_IMPORTED_MODULE_2__Company_js__["g" /* getNextCompanyPosition */])(pos);
if (nextPos == null) {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_2__Company_js__["f" /* getJobRequirementText */])(company, nextPos);
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unfortunately, you do not qualify for a promotion<br>" + reqText);
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* 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;
Player.firstJobRecvd = true;
if (leaveCompany) {
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations! You were offered a new job at " + this.companyName + " as a " +
pos.positionName + "!<br>" +
"You lost 1000 reputation at your old company " + oldCompanyName + " because you left.");
} else {
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations! You were offered a new job at " + this.companyName + " as a " + pos.positionName + "!");
}
__WEBPACK_IMPORTED_MODULE_6__engine_js__["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 = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* 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.isSecurityEngineerJob() && entryPosType.isSecurityEngineerJob()) ||
(this.companyPosition.isNetworkEngineerJob() && entryPosType.isNetworkEngineerJob()) ||
(this.companyPosition.isSecurityJob() && entryPosType.isSecurityJob()) ||
(this.companyPosition.isAgentJob() && entryPosTypeisAgentJob()) ||
(this.companyPosition.isSoftwareConsultantJob() && entryPosType.isSoftwareConsultantJob()) ||
(this.companyPosition.isBusinessConsultantJob() && entryPosType.isBusinessConsultantJob()) ||
(this.companyPosition.isPartTimeJob() && entryPosType.isPartTimeJob())) {
return Object(__WEBPACK_IMPORTED_MODULE_2__Company_js__["g" /* getNextCompanyPosition */])(this.companyPosition);
}
return entryPosType;
}
PlayerObject.prototype.applyForSoftwareJob = function(sing=false) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].SoftwareIntern, sing);
}
PlayerObject.prototype.applyForSoftwareConsultantJob = function(sing=false) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].SoftwareConsultant, sing);
}
PlayerObject.prototype.applyForItJob = function(sing=false) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].ITIntern, sing);
}
PlayerObject.prototype.applyForSecurityEngineerJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].SecurityEngineer)) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].SecurityEngineer, sing);
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForNetworkEngineerJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].NetworkEngineer)) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].NetworkEngineer, sing);
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForBusinessJob = function(sing=false) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].BusinessIntern, sing);
}
PlayerObject.prototype.applyForBusinessConsultantJob = function(sing=false) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].BusinessConsultant, sing);
}
PlayerObject.prototype.applyForSecurityJob = function(sing=false) {
//TODO If case for POlice departments
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].SecurityGuard, sing);
}
PlayerObject.prototype.applyForAgentJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].FieldAgent)) {
return this.applyForJob(__WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].FieldAgent, sing);
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForEmployeeJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].Employee)) {
Player.firstJobRecvd = true;
this.companyName = company.companyName;
this.companyPosition = __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].Employee;
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations, you are now employed at " + this.companyName);
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeEmployeeJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].PartTimeEmployee)) {
Player.firstJobRecvd = true;
this.companyName = company.companyName;
this.companyPosition = __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].PartTimeEmployee;
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations, you are now employed part-time at " + this.companyName);
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForWaiterJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].Waiter)) {
Player.firstJobRecvd = true;
this.companyName = company.companyName;
this.companyPosition = __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].Waiter;
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations, you are now employed as a waiter at " + this.companyName);
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Unforunately, you do not qualify for this position");
}
}
PlayerObject.prototype.applyForPartTimeWaiterJob = function(sing=false) {
var company = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.location]; //Company being applied to
if (this.isQualified(company, __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].PartTimeWaiter)) {
Player.firstJobRecvd = true;
this.companyName = company.companyName;
this.companyPosition = __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].PartTimeWaiter;
if (sing) {return true;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Congratulations, you are now employed as a part-time waiter at " + this.companyName);
__WEBPACK_IMPORTED_MODULE_6__engine_js__["Engine"].loadLocationContent();
} else {
if (sing) {return false;}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* 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 (typeof this.augmentations[i] === 'string' || this.augmentations[i] instanceof String) {
var newOwnedAug = new PlayerOwnedAugmentation(this.augmentations[i]);
if (this.augmentations[i] == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
newOwnedAug.level = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor].level;
}
this.augmentations[i] = newOwnedAug;
}
var augName = this.augmentations[i].name;
var aug = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][augName];
aug.owned = true;
if (aug == null) {
console.log("WARNING: Invalid augmentation name");
continue;
}
if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
for (let j = 0; j < aug.level; ++j) {
Object(__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["e" /* applyAugmentation */])(this.augmentations[i], true);
}
continue;
}
Object(__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["e" /* 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 = __WEBPACK_IMPORTED_MODULE_12__SourceFile_js__["b" /* SourceFiles */][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + this.sourceFiles[i].n);
continue;
}
Object(__WEBPACK_IMPORTED_MODULE_12__SourceFile_js__["c" /* 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 = __WEBPACK_IMPORTED_MODULE_2__Company_js__["a" /* Companies */][this.companyName];
var companyRep = 0;
if (company != null) {
companyRep = company.playerReputation;
}
//Illuminati
var illuminatiFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["ECorp"];
if (!ecorpFac.isBanned && !ecorpFac.isMember && !ecorpFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].AevumECorp && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(ecorpFac);
}
//MegaCorp
var megacorpFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["MegaCorp"];
if (!megacorpFac.isBanned && !megacorpFac.isMember && !megacorpFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12MegaCorp && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(megacorpFac);
}
//Bachman & Associates
var bachmanandassociatesFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Bachman & Associates"];
if (!bachmanandassociatesFac.isBanned && !bachmanandassociatesFac.isMember &&
!bachmanandassociatesFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].AevumBachmanAndAssociates && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(bachmanandassociatesFac);
}
//Blade Industries
var bladeindustriesFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Blade Industries"];
if (!bladeindustriesFac.isBanned && !bladeindustriesFac.isMember && !bladeindustriesFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12BladeIndustries && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(bladeindustriesFac);
}
//NWO
var nwoFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["NWO"];
if (!nwoFac.isBanned && !nwoFac.isMember && !nwoFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].VolhavenNWO && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(nwoFac);
}
//Clarke Incorporated
var clarkeincorporatedFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Clarke Incorporated"];
if (!clarkeincorporatedFac.isBanned && !clarkeincorporatedFac.isMember && !clarkeincorporatedFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].AevumClarkeIncorporated && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(clarkeincorporatedFac);
}
//OmniTek Incorporated
var omnitekincorporatedFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["OmniTek Incorporated"];
if (!omnitekincorporatedFac.isBanned && !omnitekincorporatedFac.isMember && !omnitekincorporatedFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(omnitekincorporatedFac);
}
//Four Sigma
var foursigmaFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Four Sigma"];
if (!foursigmaFac.isBanned && !foursigmaFac.isMember && !foursigmaFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12FourSigma && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* CONSTANTS */].CorpFactionRepRequirement) {
invitedFactions.push(foursigmaFac);
}
//KuaiGong International
var kuaigonginternationalFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["KuaiGong International"];
if (!kuaigonginternationalFac.isBanned && !kuaigonginternationalFac.isMember &&
!kuaigonginternationalFac.alreadyInvited &&
this.companyName == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational && companyRep >= __WEBPACK_IMPORTED_MODULE_3__Constants_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Fulcrum Secret Technologies"];
var fulcrumSecretServer = __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["b" /* 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 == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].AevumFulcrumTechnologies && companyRep >= 250000) {
invitedFactions.push(fulcrumsecrettechonologiesFac);
}
}
//BitRunners
var bitrunnersFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["BitRunners"];
var homeComp = this.getHomeComputer();
var bitrunnersServer = __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["The Black Hand"];
var blackhandServer = __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["NiteSec"];
var nitesecServer = __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Chongqing"];
if (!chongqingFac.isBanned && !chongqingFac.isMember && !chongqingFac.alreadyInvited &&
this.money.gte(20000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Chongqing) {
invitedFactions.push(chongqingFac);
}
//Sector-12
var sector12Fac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Sector-12"];
if (!sector12Fac.isBanned && !sector12Fac.isMember && !sector12Fac.alreadyInvited &&
this.money.gte(15000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12) {
invitedFactions.push(sector12Fac);
}
//New Tokyo
var newtokyoFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["New Tokyo"];
if (!newtokyoFac.isBanned && !newtokyoFac.isMember && !newtokyoFac.alreadyInvited &&
this.money.gte(20000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].NewTokyo) {
invitedFactions.push(newtokyoFac);
}
//Aevum
var aevumFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Aevum"];
if (!aevumFac.isBanned && !aevumFac.isMember && !aevumFac.alreadyInvited &&
this.money.gte(40000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Aevum) {
invitedFactions.push(aevumFac);
}
//Ishima
var ishimaFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Ishima"];
if (!ishimaFac.isBanned && !ishimaFac.isMember && !ishimaFac.alreadyInvited &&
this.money.gte(30000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Ishima) {
invitedFactions.push(ishimaFac);
}
//Volhaven
var volhavenFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Volhaven"];
if (!volhavenFac.isBanned && !volhavenFac.isMember && !volhavenFac.alreadyInvited &&
this.money.gte(50000000) && this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Volhaven) {
invitedFactions.push(volhavenFac);
}
//Speakers for the Dead
var speakersforthedeadFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12CIA &&
this.companyName != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12NSA) {
invitedFactions.push(speakersforthedeadFac);
}
//The Dark Army
var thedarkarmyFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Chongqing &&
this.numPeopleKilled >= 5 && this.karma <= -45 && this.companyName != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12CIA &&
this.companyName != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12NSA) {
invitedFactions.push(thedarkarmyFac);
}
//The Syndicate
var thesyndicateFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Aevum || this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12) &&
this.money.gte(10000000) && this.karma <= -90 &&
this.companyName != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12CIA && this.companyName != __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Sector12NSA) {
invitedFactions.push(thesyndicateFac);
}
//Silhouette
var silhouetteFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Silhouette"];
if (!silhouetteFac.isBanned && !silhouetteFac.isMember && !silhouetteFac.alreadyInvited &&
(this.companyPosition.positionName == __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].CTO.positionName ||
this.companyPosition.positionName == __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].CFO.positionName ||
this.companyPosition.positionName == __WEBPACK_IMPORTED_MODULE_2__Company_js__["d" /* CompanyPositions */].CEO.positionName) &&
this.money.gte(15000000) && this.karma <= -22) {
invitedFactions.push(silhouetteFac);
}
//Tetrads
var tetradsFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Tetrads"];
if (!tetradsFac.isBanned && !tetradsFac.isMember && !tetradsFac.alreadyInvited &&
(this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Chongqing || this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].NewTokyo ||
this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Ishima) && this.strength >= 75 && this.defense >= 75 &&
this.dexterity >= 75 && this.agility >= 75 && this.karma <= -18) {
invitedFactions.push(tetradsFac);
}
//SlumSnakes
var slumsnakesFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* 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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Netburners"];
var totalHacknetRam = 0;
var totalHacknetCores = 0;
var totalHacknetLevels = 0;
for (var i = 0; i < Player.hacknetNodes.length; ++i) {
totalHacknetLevels += Player.hacknetNodes[i].level;
totalHacknetRam += Player.hacknetNodes[i].ram;
totalHacknetCores += Player.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 = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["Tian Di Hui"];
if (!tiandihuiFac.isBanned && !tiandihuiFac.isMember && !tiandihuiFac.alreadyInvited &&
this.money.gte(1000000) && this.hacking_skill >= 50 &&
(this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Chongqing || this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].NewTokyo ||
this.city == __WEBPACK_IMPORTED_MODULE_9__Location_js__["a" /* Locations */].Ishima)) {
invitedFactions.push(tiandihuiFac);
}
//CyberSec
var cybersecFac = __WEBPACK_IMPORTED_MODULE_7__Faction_js__["b" /* Factions */]["CyberSec"];
var cybersecServer = __WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_11__SpecialServerIps_js__["b" /* 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 __WEBPACK_IMPORTED_MODULE_8__Gang_js__["b" /* Gang */]);
}
PlayerObject.prototype.startGang = function(factionName, hacking) {
this.gang = new __WEBPACK_IMPORTED_MODULE_8__Gang_js__["b" /* Gang */](factionName, hacking);
}
/************* BitNodes **************/
PlayerObject.prototype.setBitNodeNumber = function(n) {
this.bitNodeN = n;
}
/* Functions for saving and loading the Player data */
function loadPlayer(saveString) {
Player = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
//Parse Decimal.js objects
Player.money = new __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(Player.money);
Player.total_money = new __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(Player.total_money);
Player.lifetime_money = new __WEBPACK_IMPORTED_MODULE_13__utils_decimal_js___default.a(Player.lifetime_money);
}
PlayerObject.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["b" /* Generic_toJSON */])("PlayerObject", this);
}
PlayerObject.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(PlayerObject, value.data);
}
__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */].constructors.PlayerObject = PlayerObject;
let Player = new PlayerObject();
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export sizeOfObject */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addOffset; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return clearEventListeners; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getRandomInt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return compareArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return printArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return powerOfTwo; });
//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;
}
//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;}
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;
}
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;
}
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return dialogBoxCreate; });
/* Pop up Dialog Box */
let dialogBoxes = [];
//Close dialog box when clicking outside
$(document).click(function(event) {
if (dialogBoxOpened && dialogBoxes.length >= 1) {
if (!$(event.target).closest(dialogBoxes[0]).length){
dialogBoxes[0].remove();
dialogBoxes.splice(0, 1);
if (dialogBoxes.length == 0) {
dialogBoxOpened = false;
} else {
dialogBoxes[0].style.visibility = "visible";
}
}
}
});
//Dialog box close buttons
$(document).on('click', '.dialog-box-close-button', function( event ) {
if (dialogBoxOpened && dialogBoxes.length >= 1) {
dialogBoxes[0].remove();
dialogBoxes.splice(0, 1);
if (dialogBoxes.length == 0) {
dialogBoxOpened = false;
} else {
dialogBoxes[0].style.visibility = "visible";
}
}
});
var dialogBoxOpened = false;
function dialogBoxCreate(txt) {
var container = document.createElement("div");
container.setAttribute("class", "dialog-box-container");
var content = document.createElement("div");
content.setAttribute("class", "dialog-box-content");
var closeButton = document.createElement("span");
closeButton.setAttribute("class", "dialog-box-close-button");
closeButton.innerHTML = "&times;"
var textE = document.createElement("p");
textE.innerHTML = txt;
content.appendChild(closeButton);
content.appendChild(textE);
container.appendChild(content);
document.body.appendChild(container);
if (dialogBoxes.length >= 1) {
container.style.visibility = "hidden";
}
dialogBoxes.push(container);
setTimeout(function() {
dialogBoxOpened = true;
}, 400);
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CONSTANTS; });
let CONSTANTS = {
Version: "0.28.1",
//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: 30000,
BaseCostFor1GBOfRamServer: 50000, //1 GB of RAM
BaseCostFor1GBOfRamHacknetNode: 30000,
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,
//RAM Costs for different commands
ScriptWhileRamCost: 0.2,
ScriptForRamCost: 0.2,
ScriptIfRamCost: 0.1,
ScriptHackRamCost: 0.1,
ScriptGrowRamCost: 0.15,
ScriptWeakenRamCost: 0.15,
ScriptScanRamCost: 0.2,
ScriptNukeRamCost: 0.05,
ScriptBrutesshRamCost: 0.05,
ScriptFtpcrackRamCost: 0.05,
ScriptRelaysmtpRamCost: 0.05,
ScriptHttpwormRamCost: 0.05,
ScriptSqlinjectRamCost: 0.05,
ScriptRunRamCost: 0.8,
ScriptExecRamCost: 1.1,
ScriptScpRamCost: 0.5,
ScriptKillRamCost: 0.5, //Kill and killall
ScriptHasRootAccessRamCost: 0.05,
ScriptGetHostnameRamCost: 0.05,
ScriptGetHackingLevelRamCost: 0.05,
ScriptGetServerCost: 0.1,
ScriptFileExistsRamCost: 0.1,
ScriptIsRunningRamCost: 0.1,
ScriptOperatorRamCost: 0.01,
ScriptPurchaseHacknetRamCost: 1.5,
ScriptHacknetNodesRamCost: 1.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.0,
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,
MultithreadingRAMCost: 1,
//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,
//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: 100000, //Amount per clearance level
InfiltrationMoneyValue: 2000, //Convert "secret" value to money
//Stock market constants
WSEAccountCost: 200000000,
TIXAPICost: 5000000000,
StockMarketCommission: 100000,
//Hospital/Health
HospitalCostPerHp: 100000,
//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,
CrimeShoplift: "shoplift",
CrimeRobStore: "rob a store",
CrimeMug: "mug someone",
CrimeLarceny: "commit larceny",
CrimeDrugs: "deal drugs",
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. <br><br>" +
"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. <br><br>" +
"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. <br><br>" +
"<h1>Gaining root access</h1> <br>" +
"The key to hacking a server is to gain root access to that server. This can be done using " +
"the NUKE virus (NUKE.exe). You start the game with a copy of the NUKE virus on your home " +
"computer. The NUKE virus attacks the target server's open ports using buffer overflow " +
"exploits. When successful, you are granted root administrative access to the machine. <br><br>" +
"Typically, in order for the NUKE virus to succeed, the target server needs to have at least " +
"one of its ports opened. Some servers have no security and will not need any ports opened. Some " +
"will have very high security and will need many ports opened. In order to open ports on another " +
"server, you will need to run programs that attack the server to open specific ports. These programs " +
"can be coded once your hacking skill gets high enough, or they can be purchased if you can find " +
"a seller. <br><br>" +
"In order to determine how many ports need to be opened to successfully NUKE a server, connect to " +
"that server and run the 'analyze' command. This will also show you which ports have already been " +
"opened. <br><br>" +
"Once you have enough ports opened and have ran the NUKE virus to gain root access, the server " +
"can then be hacked by simply calling the 'hack' command through terminal, or by using a script.<br><br>" +
"<h1>Hacking mechanics</h1><br>" +
"When you execute the hack command, either manually through the terminal or automatically through " +
"a script, you attempt to hack the server. This action takes time. The more advanced a server's " +
"security is, the more time it will take. Your hacking skill level also affects the hacking time, " +
"with a higher hacking skill leading to shorter hacking times. Also, running the hack command " +
"manually through terminal is faster than hacking from a script. <br><br>" +
"Your attempt to hack a server will not always succeed. The chance you have to successfully hack a " +
"server is also determined by the server's security and your hacking skill level. Even if your " +
"hacking attempt is unsuccessful, you will still gain experience points. <br><br>" +
"When you successfully hack a server. You steal a certain percentage of that server's total money. This " +
"percentage is determined by the server's security and your hacking skill 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 (since you are only hacking a certain percentage). You can " +
"increase the amount of money on a server using a script and the grow() function in Netscript.<br><br>" +
"<h1>Server Security</h1><br>" +
"Each server has a security level, which is denoted by a number between 1 and 100. A higher number means " +
"the server has stronger security. As mentioned above, a server's security level is an important factor " +
"to consider when hacking. You can check a server's security level using the 'analyze' command, although this " +
"only gives an estimate (with 5% uncertainty). You can also check a server's security in a script, using the " +
"<i>getServerSecurityLevel(server)</i> function in Netscript. See the Netscript documentation for more details. " +
"This function will give you an exact value for a server's security. <br><br>" +
"Whenever a server is hacked manually or through a script, its security level increases by a small amount. Calling " +
"the grow() command in a script will also increase security level of the target server. These actions will " +
"make it harder for you to hack the server, and decrease the amount of money you can steal. You can lower a " +
"server's security level in a script using the <i>weaken(server)</i> function in Netscript. See the Netscript " +
"documentation for more details.<br><br>" +
"A server has a minimum security level that is equal to one third of its starting security, rounded to the " +
"nearest integer. To be more precise:<br><br>" +
"server.minSecurityLevel = Math.max(1, Math.round(server.startingSecurityLevel / 3))<br><br>" +
"This means that a server's security will not fall below this value if you are trying to weaken it.",
TutorialScriptsText: "Scripts can be used to automate the hacking process. Scripts must be written in the Netscript language. " +
"Documentation about the Netscript language can be found in the 'Netscript Programming Language' " +
"section of this 'Tutorial' page. <br><br> " +
"<strong>It is highly recommended that you have a basic background in programming to start writing scripts. " +
"You by no means need to be an expert. All you need is some familiarity with basic programming " +
"constructs like for/while loops, if statements, " +
"functions, variables, etc. The Netscript programming language most resembles the Javascript language. " +
"Therefore, a good beginner's programming tutorial to read might be <a href='https://www.w3schools.com/js/default.asp' target='_blank'>" +
"this one</a>. Note that while the Netscript language is similar to Javascript, it is not the exact same, so the " +
"syntax will vary a little bit. </strong> <br><br>" +
"Running a script requires RAM. The more complex a script is, the more RAM " +
"it requires to run. Scripts can be run on any server you have root access to. <br><br>" +
"Here are some Terminal commands that are useful when working with scripts: <br><br>" +
"<i>check [script] [args...]</i><br>Prints the logs of the script specified by the name and arguments to Terminal. Arguments should be separated " +
"by a space. Note that scripts are uniquely " +
"identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the argument 'foodnstuff' then in order to 'check' it you must " +
"also add the 'foodnstuff' argument to the check command as so: <br>check foo.script foodnstuff<br><br>" +
"<i>free</i><br>Shows the current server's RAM usage and availability <br><br>" +
"<i>kill [script] [args...]</i><br>Stops a script that is running with the specified script name and arguments. " +
"Arguments should be separated by a space. Note that " +
"scripts are uniquely identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the " +
"argument 1 and 2, then just typing 'kill foo.script' will not work. You have to use 'kill foo.script 1 2'. <br><br>" +
"<i>mem [script] [-t] [n]</i><br>Check how much RAM a script requires to run with n threads<br><br>" +
"<i>nano [script]</i><br>Create/Edit a script. The name of the script must end with the '.script' extension <br><br>" +
"<i>ps</i><br>Displays all scripts that are actively running on the current server<br><br>" +
"<i>rm [script]</i><br>Delete a script<br><br>" +
"<i>run [script] [-t] [n] [args...]</i><br>Run a script with n threads and the specified arguments. Each argument should be separated by a space. " +
"Both the arguments and thread specification are optional. If neither are specified, then the script will be run single-threaded with no arguments.<br>" +
"Examples:<br>run foo.script<br>The command above will run 'foo.script' single-threaded with no arguments." +
"<br>run foo.script -t 10<br>The command above will run 'foo.script' with 10 threads and no arguments." +
"<br>run foo.script foodnstuff sigma-cosmetics 10<br>The command above will run 'foo.script' single-threaded with three arguments: [foodnstuff, sigma-cosmetics, 10]" +
"<br>run foo.script -t 50 foodnstuff<br>The command above will run 'foo.script' with 50 threads and a single argument: [foodnstuff]<br><br>" +
"<i>tail [script] [args...]</i><br>Displays the logs of the script specified by the name and arguments. Note that scripts are uniquely " +
"identified by their arguments as well as their name. For example, if you ran a script 'foo.script' with the argument 'foodnstuff' then in order to 'tail' it you must " +
"also add the 'foodnstuff' argument to the tail command as so: <br>tail foo.script foodnstuff<br><br>" +
"<i>top</i><br>Displays all active scripts and their RAM usage <br><br>" +
"<u><h1> Multithreading scripts </h1></u><br>" +
"Scripts can be multithreaded. A multithreaded script runs the script's code once in each thread. The result is that " +
"every call to the hack(), grow(), and weaken() Netscript functions will have its effect multiplied by the number of threads. " +
"For example, if a normal single-threaded script is able to hack $10,000, then running the same script with 5 threads would " +
"yield $50,000. <br><br> " +
"When multithreading a script, the total RAM cost can be calculated by simply multiplying the base RAM cost of the script " +
"with the number of threads, where the base cost refers to the amount of RAM required to run the script single-threaded. " +
"In the terminal, you can run the " +
"'mem [scriptname] -t n' command to see how much RAM a script requires with n threads. <br><br>" +
"Every method for running a script has an option for making it multihreaded. To run a script with " +
"n threads from a Terminal: <br>" +
"run [scriptname] -t n<br><br>" +
"Using Netscript commands: <br>" +
"run('scriptname.script', n);<br> " +
"exec('scriptname.script, 'targetServer', n);<br><br>" +
"<u><h1> Notes about how scripts work offline </h1> </u><br>" +
"<strong> The scripts that you write and execute are interpreted in Javascript. For this " +
"reason, it is not possible for these scripts to run while offline (when the game is closed). " +
"It is important to note that for this reason, conditionals such as if/else statements and certain " +
"commands such as purchaseHacknetNode() or nuke() will not work while the game is offline.<br><br>" +
"However, Scripts WILL continue to generate money and hacking exp for you while the game is offline. This " +
"offline production is based off of the scripts' production while the game is online. <br><br>" +
"grow() and weaken() are two Netscript commands that will also be applied when the game is offline, although at a slower rate " +
"compared to if the game was open. This is done by having each script keep track of the " +
"rate at which the grow() and weaken() commands are called when the game is online. These calculated rates are used to determine how many times " +
"these function calls would be made while the game is offline. <br><br> " +
"Also, note that because of the way the Netscript interpreter is implemented, " +
"whenever you reload or re-open the game all of the scripts that you are running will " +
"start running from the BEGINNING of the code. The game does not keep track of where exactly " +
"the execution of a script is when it saves/loads. </strong><br><br>",
TutorialNetscriptText: "Netscript is a programming language implemented for this game. The language has " +
"your basic programming constructs and several built-in commands that are used to hack. <br><br>" +
"<u><h1>Official Wiki and Documentation</h1></u><br>" +
"<a href='https://bitburner.wikia.com/wiki/Netscript' target='_blank'>Check out Bitburner's wiki for the official Netscript documentation</a>" +
". The wiki documentation will contain more details and " +
"code examples than this documentation page. Also, it can be opened up in another tab/window for convenience!<br><br>" +
"<u><h1> Variables and data types </h1></u><br>" +
"The following data types are supported by Netscript: <br>" +
"numeric - Integers and floats (eg. 6, 10.4999)<br>" +
"string - Encapsulated by single or double quotes (eg. 'this is a string')<br>" +
"boolean - true or false<br><br>" +
"Strings are fully functional <a href='https://www.w3schools.com/jsref/jsref_obj_string.asp' target='_blank'>Javascript strings</a>, " +
"which means that all of the member functions of Javascript strings such as toLowerCase() and includes() are also " +
"available in Netscript!<br><br>" +
"To create a variable, use the assign (=) operator. The language is not strongly typed. Examples: <br>" +
"i = 5;<br>" +
"s = 'this game is awesome!';<br><br>" +
"In the first example above, we are creating the variable i and assigning it a value of 5. In the second, " +
"we are creating the variable s and assigning it the value of a string. Note that all expressions must be " +
"ended with a semicolon. <br><br>" +
"<u><h1> Operators</h1> </u><br>" +
"The following operators are supported by Netscript: <br>" +
"&nbsp;+<br>" +
"&nbsp;-<br>" +
"&nbsp;*<br>" +
"&nbsp;/<br>" +
"&nbsp;%<br>" +
"&nbsp;&&<br>" +
"&nbsp;||<br>" +
"&nbsp;<<br>" +
"&nbsp;><br>" +
"&nbsp;<=<br>" +
"&nbsp;>=<br>" +
"&nbsp;==<br>" +
"&nbsp;!=<br>" +
"&nbsp;++ (Note: This ONLY pre-increments. Post-increment does not work)<br>" +
"&nbsp;-- (Note: This ONLY pre-decrements. Post-decrement does not work)<br>" +
"&nbsp;- (Negation operator)<br>" +
"&nbsp;!<br><br>" +
"<u><h1> Arrays </h1></u><br>" +
"Netscript arrays have the same properties and functions as javascript arrays. For information see javascripts <a href=\"https://www.w3schools.com/js/js_arrays.asp\" target='_blank'>array</a> documentation.<br><br>"+
"<u><h1> Script Arguments </h1></u><br>" +
"Arguments passed into a script can be accessed using a special array called 'args'. The arguments can be accessed like a normal array using the [] " +
"operator. (args[0], args[1], args[2]...) <br><br>" +
"For example, let's say we want to make a generic script 'generic-run.script' and we plan to pass two arguments into that script. The first argument will be the name of " +
"another script, and the second argument will be a number. This generic script will run the script specified in the first argument " +
"with the amount of threads specified in the second element. The code would look like:<br><br>" +
"run(args[0], args[1]);<br><br>" +
"It is also possible to get the number of arguments that was passed into a script using:<br><br>" +
"args.length<br><br>" +
"Note that none of the other functions that typically work with arrays, such as remove(), insert(), clear(), etc., will work on the " +
"args array.<br><br>" +
"<u><h1> Functions </h1></u><br>" +
"You can NOT define you own functions in Netscript (yet), but there are several built in functions that " +
"you may use: <br><br> " +
"<i>hack(hostname/ip)</i><br>Core function that is used to try and hack servers to steal money and gain hacking experience. The argument passed in must be a string with " +
"either the IP or hostname of the server you want to hack. The runtime for this command depends on your hacking level and the target server's security level. " +
" A script can hack a server from anywhere. It does not need to be running on the same server to hack that server. " +
"For example, you can create a script that hacks the 'foodnstuff' server and run that script on any server in the game. A successful hack() on " +
"a server will raise that server's security level by 0.002. Returns true if the hack is successful and " +
"false otherwise. <br>" +
"Examples: hack('foodnstuff'); or hack('148.192.0.12');<br><br>" +
"<i>sleep(n, log=true)</i><br>Suspends the script for n milliseconds. The second argument is an optional boolean that indicates " +
"whether or not the function should log the sleep action. If this argument is true, then calling this function will write " +
"'Sleeping for N milliseconds' to the script's logs. If it's false, then this function will not log anything. " +
"If this argument is not specified then it will be true by default. <br>Example: sleep(5000);<br><br>" +
"<i>grow(hostname/ip)</i><br>Use your hacking skills to increase the amount of money available on a server. The argument passed in " +
"must be a string with either the IP or hostname of the target server. The runtime for this command depends on your hacking level and the target server's security level. " +
"When grow() completes, the money available on a target server will be increased by a certain, fixed percentage. This percentage " +
"is determined by the server's growth rate and varies between servers. Generally, higher-level servers have higher growth rates. <br><br> " +
"Like hack(), grow() can be called on any server, regardless of where the script is running. " +
"The grow() command requires root access to the target server, but there is no required hacking level to run the command. " +
"It also raises the security level of the target server by 0.004. " +
"Returns the number by which the money on the server was multiplied for the growth. " +
"Works offline at a slower rate. <br> Example: grow('foodnstuff');<br><br>" +
"<i>weaken(hostname/ip)</i><br>Use your hacking skills to attack a server's security, lowering the server's security level. The argument passed " +
"in must be a string with either the IP or hostname of the target server. The runtime for this command depends on your " +
"hacking level and the target server's security level. This function lowers the security level of the target server by " +
"0.05.<br><br> Like hack() and grow(), weaken() can be called on " +
"any server, regardless of where the script is running. This command requires root access to the target server, but " +
"there is no required hacking level to run the command. Returns " +
"0.1. Works offline at a slower rate<br> Example: weaken('foodnstuff');<br><br>" +
"<i>print(x)</i><br>Prints a value or a variable to the scripts logs (which can be viewed with the 'tail [script]' terminal command ). <br><br>" +
"<i>tprint(x)</i><br>Prints a value or a variable to the Terminal<br><br>" +
"<i>clearLog()</i><br>Clears the script's logs. <br><br>" +
"<i>scan(hostname/ip)</i><br>Returns an array containing the hostnames of all servers that are one node away from the specified server. " +
"The argument must be a string containing the IP or hostname of the target server. The hostnames in the returned array are strings.<br><br>" +
"<i>nuke(hostname/ip)</i><br>Run NUKE.exe on the target server. NUKE.exe must exist on your home computer. Does NOT work while offline <br> Example: nuke('foodnstuff'); <br><br>" +
"<i>brutessh(hostname/ip)</i><br>Run BruteSSH.exe on the target server. BruteSSH.exe must exist on your home computer. Does NOT work while offline <br> Example: brutessh('foodnstuff');<br><br>" +
"<i>ftpcrack(hostname/ip)</i><br>Run FTPCrack.exe on the target server. FTPCrack.exe must exist on your home computer. Does NOT work while offline <br> Example: ftpcrack('foodnstuff');<br><br>" +
"<i>relaysmtp(hostname/ip)</i><br>Run relaySMTP.exe on the target server. relaySMTP.exe must exist on your home computer. Does NOT work while offline <br> Example: relaysmtp('foodnstuff');<br><br>" +
"<i>httpworm(hostname/ip)</i><br>Run HTTPWorm.exe on the target server. HTTPWorm.exe must exist on your home computer. Does NOT work while offline <br> Example: httpworm('foodnstuff');<br><br>" +
"<i>sqlinject(hostname/ip)</i><br>Run SQLInject.exe on the target server. SQLInject.exe must exist on your home computer. Does NOT work while offline <br> Example: sqlinject('foodnstuff');<br><br>" +
"<i>run(script, [numThreads], [args...])</i> <br> Run a script as a separate process. The first argument that is passed in is the name of the script as a string. This function can only " +
"be used to run scripts located on the current server (the server running the script that calls this function). The second argument " +
"is optional, and it specifies how many threads to run the script with. This argument must be a number greater than 0. If it is omitted, then the script will be run single-threaded. Any additional arguments will specify " +
"arguments to pass into the new script that is being run. If arguments are specified for the new script, then the second argument numThreads argument must be filled in with a value.<br><br>" +
"Returns true if the script is successfully started, and false otherwise. Requires a significant amount " +
"of RAM to run this command. Does NOT work while offline <br><br>" +
"The simplest way to use the run command is to call it with just the script name. The following example will run 'foo.script' single-threaded with no arguments:<br><br>" +
"run('foo.script');<br><br>" +
"The following example will run 'foo.script' but with 5 threads instead of single-threaded:<br><br>" +
"run('foo.script', 5);<br><br>" +
"The following example will run 'foo.script' single-threaded, and will pass the string 'foodnstuff' into the script as an argument:<br><br>" +
"run('foo.script', 1, 'foodnstuff');<br><br>" +
"<i>exec(script, hostname/ip, [numThreads], [args...])</i><br>Run a script as a separate process on another server. The first argument is the name of the script as a string. The " +
"second argument is a string with the hostname or IP of the 'target server' on which to run the script. The specified script must exist on the target server. " +
"The third argument is optional, and it specifies how many threads to run the script with. If it is omitted, then the script will be run single-threaded. " +
"This argument must be a number that is greater than 0. Any additional arguments will specify arguments to pass into the new script that is being run. If " +
"arguments are specified for the new script, then the third argument numThreads must be filled in with a value.<br><br>Returns " +
"true if the script is successfully started, and false otherwise. Does NOT work while offline<br><br> " +
"The simplest way to use the exec command is to call it with just the script name and the target server. The following example will try to run 'generic-hack.script' " +
"on the 'foodnstuff' server:<br><br>" +
"exec('generic-hack.script', 'foodnstuff');<br><br>" +
"The following example will try to run the script 'generic-hack.script' on the 'joesguns' server with 10 threads:<br><br>" +
"exec('generic-hack.script', 'joesguns', 10);<br><br>" +
"The following example will try to run the script 'foo.script' on the 'foodnstuff' server with 5 threads. It will also pass the number 1 and the string 'test' in as arguments " +
"to the script.<br><br>" +
"exec('foo.script', 'foodnstuff', 5, 1, 'test');<br><br>" +
"<i>kill(script, hostname/ip, [args...])</i><br> Kills the script on the target server specified by the script's name and arguments. Remember that " +
"scripts are uniquely identified by both their name and arguments. For example, if 'foo.script' is run with the argument 1, then this is not the " +
"same as 'foo.script' run with the argument 2, even though they have the same code. <br><br>" +
"The first argument must be a string with the name of the script. The name is case-sensitive. " +
"The second argument must be a string with the hostname or IP of the target server. Any additional arguments to the function will specify the arguments passed " +
"into the script that should be killed. <br><br>The function will try to kill the specified script on the target server. " +
"If the script is found on the specified server and is running, then it will be killed and this function " +
"will return true. Otherwise, this function will return false. <br><br>" +
"Examples:<br>" +
"If you are trying to kill a script named 'foo.script' on the 'foodnstuff' server that was ran with no arguments, use this:<br><br>" +
"kill('foo.script', 'foodnstuff');<br><br>" +
"If you are trying to kill a script named 'foo.script' on the current server that was ran with no arguments, use this:<br><br>" +
"kill('foo.script', getHostname());<br><br>" +
"If you are trying to kill a script named 'foo.script' on the current server that was ran with the arguments 1 and 'foodnstuff', use this:<br><br>" +
"kill('foo.script', getHostname(), 1, 'foodnstuff');<br><br>" +
"<i>killall(hostname/ip)</i><br> Kills all running scripts on the specified server. This function takes a single argument which " +
"must be a string containing the hostname or IP of the target server. This function will always return true. <br><br>" +
"<i>scp(script, hostname/ip)</i><br>Copies a script to another server. The first argument is a string with the filename of the script " +
"to be copied. The second argument is a string with the hostname or IP of the destination server. Returns true if the script is successfully " +
"copied over and false otherwise. <br> Example: scp('hack-template.script', 'foodnstuff');<br><br>" +
"<i>hasRootAccess(hostname/ip)</i><br> Returns a boolean (true or false) indicating whether or not the Player has root access to a server. " +
"The argument passed in must be a string with either the hostname or IP of the target server. Does NOT work while offline.<br> " +
"Example:<br>if (hasRootAccess('foodnstuff') == false) {<br>&nbsp;&nbsp;&nbsp;&nbsp;nuke('foodnstuff');<br>}<br><br>" +
"<i>getHostname()</i><br>Returns a string with the hostname of the server that the script is running on<br><br>" +
"<i>getHackingLevel()</i><br> Returns the Player's current hacking level. Does NOT work while offline <br><br> " +
"<i>getServerMoneyAvailable(hostname/ip)</i><br> Returns the amount of money available on a server. The argument passed in must be a string with either the " +
"hostname or IP of the target server. Does NOT work while offline <br> Example: getServerMoneyAvailable('foodnstuff');<br><br>" +
"<i>getServerMaxMoney(hostname/ip)</i><br>Returns the maximum amount of money that can be available on a server. The argument passed in must be a string with " +
"the hostname or IP of the target server. Does NOT work while offline<br>Example: getServerMaxMoney('foodnstuff');<br><br>" +
"<i>getServerGrowth(hostname/ip)</i><br>Returns the server's intrinsic 'growth parameter'. This growth parameter is a number " +
"between 1 and 100 that represents how quickly the server's money grows. This parameter affects the percentage by which this server's " +
"money is increased when using the grow() function. A higher growth parameter will result in a higher percentage from grow().<br><br>" +
"The argument passed in must be a string with the hostname or IP of the target server.<br><br>" +
"<i>getServerSecurityLevel(hostname/ip)</i><br>Returns the security level of a server. The argument passed in must be a string with either the " +
"hostname or IP of the target server. A server's security is denoted by a number between 1 and 100. Does NOT work while offline.<br><br>" +
"<i>getServerBaseSecurityLevel(hostname/ip)</i><br> Returns the base security level of a server. This is the security level that the server starts out with. " +
"This is different than getServerSecurityLevel() because getServerSecurityLevel() returns the current security level of a server, which can constantly change " +
"due to hack(), grow(), and weaken() calls on that server. The base security level will stay the same until you reset by installing an Augmentation. <br><br>" +
"The argument passed in must be a string with either the hostname or IP of the target server. A server's base security is denoted by a number between 1 and 100. " +
"Does NOT work while offline.<br><br>" +
"<i>getServerRequiredHackingLevel(hostname/ip)</i><br>Returns the required hacking level of a server. The argument passed in must be a string with either the " +
"hostname or IP or the target server. Does NOT work while offline <br><br>" +
"<i>getServerNumPortsRequired(hostname/ip)</i><br>Returns the number of open ports required to successfully run NUKE.exe on a server. The argument " +
"passed in must be a string with either the hostname or IP of the target server. Does NOT work while offline<br><br>" +
"<i>getServerRam(hostname/ip)</i><br>Returns an array with two elements that gives information about the target server's RAM. The first " +
"element in the array is the amount of RAM that the server has (in GB). The second element in the array is the amount of RAM that " +
"is currently being used on the server.<br><br>" +
"<i>fileExists(filename, [hostname/ip])</i><br> Returns a boolean (true or false) indicating whether the specified file exists on a server. " +
"The first argument must be a string with the name of the file. A file can either be a script or a program. A script name is case-sensitive, but a " +
"program is not. For example, fileExists('brutessh.exe') will work fine, even though the actual program is named BruteSSH.exe. <br><br> " +
"The second argument is a string with the hostname or IP of the server on which to search for the program. This second argument is optional. " +
"If it is omitted, then the function will search through the current server (the server running the script that calls this function) for the file. <br> " +
"Example: fileExists('foo.script', 'foodnstuff');<br>" +
"Example: fileExists('ftpcrack.exe');<br><br>" +
"The first example above will return true if the script named 'foo.script' exists on the 'foodnstuff' server, and false otherwise. The second example above will " +
"return true if the current server (the server on which this function runs) contains the FTPCrack.exe program, and false otherwise. <br><br>" +
"<i>isRunning(filename, hostname/ip, [args...])</i><br> Returns a boolean (true or false) indicating whether the specified script is running on a server. " +
"Remember that a script is uniquely identified by both its name and its arguments. <br><br>" +
"The first argument must be a string with the name of the script. The script name is case sensitive. The second argument is a string with the " +
"hostname or IP of the target server. Any additional arguments passed to the function will specify the arguments passed into the target script. " +
"The function will check whether the script is running on that target server.<br>" +
"Example: isRunning('foo.script', 'foodnstuff');<br>" +
"Example: isRunning('foo.script', getHostname());<br>" +
"Example: isRunning('foo.script', 'joesguns', 1, 5, 'test');<br><br>" +
"The first example above will return true if there is a script named 'foo.script' with no arguments running on the 'foodnstuff' server, and false otherwise. The second " +
"example above will return true if there is a script named 'foo.script' with no arguments running on the current server, and false otherwise. " +
"The third example above will return true if there is a script named 'foo.script' with the arguments 1, 5, and 'test' running on the 'joesguns' server, and " +
"false otherwise.<br><br>" +
"<i>getNextHacknetNodeCost()</i><br>Returns the cost of purchasing a new Hacknet Node<br><br>" +
"<i>purchaseHacknetNode()</i><br>Purchases a new Hacknet Node. Returns a number with the index of the Hacknet Node. This index is equivalent to the number " +
"at the end of the Hacknet Node's name (e.g The Hacknet Node named 'hacknet-node-4' will have an index of 4). If the player cannot afford to purchase " +
"a new Hacknet Node then the function will return false. Does NOT work offline<br><br>" +
"<i>purchaseServer(hostname, ram)</i><br> Purchases a server with the specified hostname and amount of RAM. The first argument can be any data type, " +
"but it will be converted to a string using Javascript's String function. Anything that resolves to an empty string will cause the function to fail. " +
"The second argument specified the amount of RAM (in GB) for the server. This argument must resolve to a numeric and it must be a power of 2 " +
"(2, 4, 8, etc...). <br><br>" +
"Purchasing a server using this Netscript function is twice as expensive as manually purchasing a server from a location in the World.<br><br>" +
"This function returns the hostname of the newly purchased server as a string. If the function fails to purchase a server, then it will return " +
"an empty string. The function will fail if the arguments passed in are invalid or if the player does not have enough money to purchase the specified server.<br><br>" +
"<i>round(n)</i><br>Rounds the number n to the nearest integer. If the argument passed in is not a number, then the function will return 0.<br><br>" +
"<i>write(port, data)</i><br>Writes data to a port. The first argument must be a number between 1 and 10 that specifies the port. The second " +
"argument defines the data to write to the port. If the second argument is not specified then it will write an empty string to the port.<br><br>" +
"<i>read(port)</i><br>Reads data from a port. The first argument must be a number between 1 and 10 that specifies the port. A port is a serialized queue. " +
"This function will remove the first element from the queue and return it. If the queue is empty, then the string 'NULL PORT DATA' will be returned. <br><br>" +
"<i>scriptRunning(scriptname, hostname/ip)</i><br>Returns a boolean indicating whether any instance of the specified script is running " +
"on a server, regardless of its arguments. This is different than the isRunning() function because it does not " +
"try to identify a specific instance of a running script by its arguments.<br><br>" +
"The first argument must be a string with the name of the script. The script name is case sensitive. The second argument is " +
"a string with the hostname or IP of the target server. Both arguments are required.<br><br>" +
"<i>scriptKill(scriptname, hostname/ip)</i><br>Kills all scripts with the specified filename that are running on the server specified by the " +
"hostname/ip, regardless of arguments. Returns true if one or more scripts were successfully killed, and false if there were none. <br><br>" +
"The first argument must be a string with the name of the script. The script name is case sensitive. The second argument is " +
"a string with the hostname or IP of the target server. Both arguments are required.<br><br>" +
"<i>getScriptRam(scriptname, hostname/ip)</i><br>Returns the amount of RAM required to run the specified script on the " +
"target server. The first argument must be a string with the name of the script. The script name is case sensitive. " +
"The second argument is a string with the hostname or IP of the server where that script is. Both arguments are required.<br><br>" +
"<i>getHackTime(hostname/ip)</i><br>Returns the amount of time in seconds it takes to execute the hack() Netscript function " +
"on the server specified by the hostname/ip. The argument must be a string with the hostname/ip of the target server.<br><br>" +
"<i>getGrowTime(hostname/ip)</i><br>Returns the amount of time in seconds it takes to execute the grow() Netscript function " +
"on the server specified by the hostname/ip. The argument must be a string with the hostname/ip of the target server.<br><br>" +
"<i>getWeakenTime(hostname/ip)</i><br>Returns the amount of time in seconds it takes to execute the weaken() Netscript function " +
"on the server specified by the hostname/ip. The argument must be a string with the hostname/ip of the target server.<br><br>" +
"<u><h1>Hacknet Nodes API</h1></u><br>" +
"Netscript provides the following API for accessing and upgrading your Hacknet Nodes through scripts. This API does NOT work offline.<br><br>" +
"<i>hacknetnodes</i><br> A special variable. This is an array that maps to the Player's Hacknet Nodes. The Hacknet Nodes are accessed through " +
"indexes. These indexes correspond to the number at the end of the name of the Hacknet Node. For example, the first Hacknet Node you purchase " +
"will have the same 'hacknet-node-0' and can be accessed with hacknetnodes[0]. The fourth Hacknet Node you purchase will have the name " +
"'hacknet-node-3' and can be accessed with hacknetnodes[3]. <br><br>" +
"<i>hacknetnodes.length</i><br> Returns the number of Hacknet Nodes that the player owns<br><br>" +
"<i>hacknetnodes[i].level</i><br> Returns the level of the corresponding Hacknet Node<br><br>" +
"<i>hacknetnodes[i].ram</i><br> Returns the amount of RAM on the corresponding Hacknet Node<br><br>" +
"<i>hacknetnodes[i].cores</i><br> Returns the number of cores on the corresponding Hacknet Node<br><br>" +
"<i>hacknetnodes[i].upgradeLevel(n)</i><br> Tries to upgrade the level of the corresponding Hacknet Node n times. The argument n must be a " +
"positive integer. Returns true if the Hacknet Node's level is successfully upgraded n times or up to the max level (200), and false otherwise.<br><br>" +
"<i>hacknetnodes[i].upgradeRam()</i><br> Tries to upgrade the amount of RAM on the corresponding Hacknet Node. Returns true if the " +
"RAM is successfully upgraded, and false otherwise. <br><br>" +
"<i>hacknetnodes[i].upgradeCore()</i><br> Attempts to purchase an additional core for the corresponding Hacknet Node. Returns true if the " +
"additional core is successfully purchase, and false otherwise. <br><br>" +
"Example: The following is an example of one way a script can be used to automate the purchasing and upgrading of Hacknet Nodes. " +
"This script purchases new Hacknet Nodes until the player has four. Then, it iteratively upgrades each of those four Hacknet Nodes " +
"to a level of at least 75, RAM to at least 8GB, and number of cores to at least 2.<br><br>" +
"while(hacknetnodes.length < 4) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;purchaseHacknetNode();<br>" +
"}<br>" +
"for (i = 0; i < 4; i = i++) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;while (hacknetnodes[i].level <= 75) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hacknetnodes[i].upgradeLevel(5);<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sleep(10000);<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;}<br>" +
"}<br>" +
"for (i = 0; i < 4; i = i++) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;while (hacknetnodes[i].ram < 8) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hacknetnodes[i].upgradeRam();<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sleep(10000);<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;}<br>" +
"}<br>" +
"for (i = 0; i < 4; i = i++) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;while (hacknetnodes[i].cores < 2) {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hacknetnodes[i].upgradeCore();<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sleep(10000);<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;}<br>" +
"}<br><br>" +
"<u><h1>Trade Information eXchange (TIX) API</h1></u><br>" +
"<i>getStockPrice(sym)</i><br>Returns the price of a stock. The argument passed in must be the stock's symbol (NOT THE COMPANY NAME!). The symbol " +
"is a sequence of two to four capital letters. The symbol argument must be a string. <br><br>" +
"Example: getStockPrice('FSIG');<br><br>" +
"<i>getStockPosition(sym)</i><br>Returns an array of two elements that represents the player's position in a stock. The first element " +
"in the array is the number of shares the player owns of the specified stock. The second element in the array is the average price of the player's " +
"shares. Both elements are numbers. The argument passed in must be the stock's symbol, which is a sequence of two to four capital letters.<br><br>" +
"Example: <br><br>pos = getStockPosition('ECP');<br>shares = pos[0];<br>avgPx = pos[1];<br><br>"+
"<i>buyStock(sym, shares)</i><br>Attempts to purchase shares of a stock. The first argument must be a string with the stock's symbol. The second argument " +
"must be the number of shares to purchase.<br><br>" +
"If the player does not have enough money to purchase specified number of shares, then no shares will be purchased (it will not purchase the most you can afford). " +
"Remember that every transaction on the stock exchange costs a certain commission fee.<br><br>" +
"The function will return true if it successfully purchases the specified number of shares of stock, and false otherwise.<br><br>" +
"<i>sellStock(sym, shares)</i><br>Attempts to sell shares of a stock. The first argument must be a string with the stock's symbol. The second argument " +
"must be the number of shares to sell.<br><br>" +
"If the specified number of shares in the function exceeds the amount that the player actually owns, then this function will sell all owned shares. " +
"Remember that every transaction on the stock exchange costs a certain commission fee.<br><br>" +
"The net profit made from selling stocks with this function is reflected in the script's statistics. This net profit is calculated as: <br><br>" +
"shares * (sell price - average price of purchased shares)<br><br>" +
"This function will return true if the shares of stock are successfully sold and false otherwise.<br><br>" +
"<u><h1>While loops </h1></u><br>" +
"A while loop is a control flow statement that repeatedly executes code as long as a condition is met. <br><br> " +
"<i>while (<i>[cond]</i>) {<br>&nbsp;&nbsp;&nbsp;&nbsp;<i>[code]</i><br>}</i><br><br>" +
"As long as <i>[cond]</i> remains true, the code block <i>[code]</i> will continuously execute. Example: <br><br>" +
"<i>i = 0; <br> while (i < 10) { <br>&nbsp;&nbsp;&nbsp;&nbsp;hack('foodnstuff');<br>&nbsp;&nbsp;&nbsp;&nbsp;i = i + 1;<br> } </i><br><br>" +
"This code above repeats the 'hack('foodnstuff')' command 10 times before it stops and exits. <br><br>" +
"<i>while(true) { <br>&nbsp;&nbsp;&nbsp;&nbsp; hack('foodnstuff'); <br> }</i><br><br> " +
"This while loop above is an infinite loop (continuously runs until the script is manually stopped) that repeatedly runs the 'hack('foodnstuff')' command. " +
"Note that a semicolon is needed at closing bracket of the while loop, UNLESS it is at the end of the code<br><br> " +
"<u><h1>For loops</h1></u><br>" +
"A for loop is another control flow statement that allows code to be repeated by iterations. The structure is: <br><br> " +
"<i>for (<i>[init]</i>; <i>[cond]</i>; <i>[post]</i>) {<br>&nbsp;&nbsp;&nbsp;&nbsp;<i>code</i> <br> } </i><br><br>" +
"The <i>[init]</i> expression evaluates before the for loop begins. The for loop will continue to execute " +
"as long as <i>[cond]</i> is met. The <i>[post]</i> expression will evaluate at the end of every iteration " +
"of the for loop. The following example shows code that will run the 'hack('foodnstuff');' command 10 times " +
" using a for loop: <br><br>" +
"<i>for (i = 0; i < 10; i = i++) { <br>&nbsp;&nbsp;&nbsp;&nbsp;hack('foodnstuff');<br>} </i><br><br>" +
"<u><h1> If statements </h1></u><br>" +
"If/Else if/Else statements are conditional statements used to perform different actions based on different conditions: <br><br>" +
"<i>if (condition1) {<br>&nbsp;&nbsp;&nbsp;&nbsp;code1<br>} else if (condition2) {<br>&nbsp;&nbsp;&nbsp;&nbsp;code2<br>} else {<br>" +
"&nbsp;&nbsp;&nbsp;&nbsp;code3<br>}</i><br><br>" +
"In the code above, first <i>condition1</i> will be checked. If this condition is true, then <i>code1</i> will execute and the " +
"rest of the if/else if/else statement will be skipped. If <i>condition1</i> is NOT true, then the code will then go on to check " +
"<i>condition2</i>. If <i>condition2</i> is true, then <i>code2</i> will be executed, and the rest of the if/else if/else statement " +
"will be skipped. If none of the conditions are true, then the code within the else block (<i>code3</i>) will be executed. " +
"Note that a conditional statement can have any number of 'else if' statements. <br><br>" +
"Example: <br><br>" +
"if(getServerMoneyAvailable('foodnstuff') > 200000) {<br>&nbsp;&nbsp;&nbsp;&nbsp;hack('foodnstuff');<br>" +
"} else {<br>&nbsp;&nbsp;&nbsp;&nbsp;grow('foodnstuff');<br>}<br><br>" +
"The code above will use the getServerMoneyAvailable() function to check how much money there is on the 'foodnstuff' server. " +
"If there is more than $200,000, then it will try to hack that server. If there is $200,000 or less on the server, " +
"then the code will call grow('foodnstuff') instead and add more money to the server.<br><br>",
TutorialSingularityFunctionsText: "<u><h1>Singularity Functions</h1></u><br>" +
"The Singularity Functions are a special set of Netscript functions that are unlocked in BitNode-4. " +
"These functions allow you to control many additional aspects of the game through scripts, such as " +
"working for factions/companies, purchasing/installing Augmentations, and creating programs.<br><br>" +
"If you are in BitNode-4, then you will automatically have access to all of these functions. " +
"You can use the Singularity Functions in other BitNodes if and only if you have the Source-File " +
"for BitNode-4 (aka Source-File 4). Each level of Source-File 4 will open up additional Singularity " +
"Functions that you can use in other BitNodes. If your Source-File 4 is upgraded all the way to level 3, " +
"then you will be able to access all of the Singularity Functions.<br><br>" +
"Note that Singularity Functions require a lot of RAM outside of BitNode-4 (their RAM costs are multiplied by " +
"10 if you are not in BitNode-4).<br><br>" +
"<i>universityCourse(universityName, courseName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically set you to start taking a course at a university. If you are already " +
"in the middle of some 'working' action (such as working at a company, for a faction, or on a program), " +
"then running this function will automatically cancel that action and give you your earnings.<br><br>" +
"The first argument must be a string with the name of the university. The names are NOT case-sensitive. " +
"Note that you must be in the correct city for whatever university you specify. The three universities are:<br><br>" +
"Summit University<br>Rothman University<br>ZB Institute of Technology<br><br>" +
"The second argument must be a string with the name of the course you are taking. These names are NOT case-sensitive. " +
"The available courses are:<br><br>" +
"Study Computer Science<br>Data Structures<br>Networks<br>Algorithms<br>Management<br>Leadership<br><br>" +
"The cost and experience gains for all of these universities and classes are the same as if you were to manually " +
"visit and take these classes.<br><br>" +
"This function will return true if you successfully start taking the course, and false otherwise.<br><br>" +
"<i>gymWorkout(gymName, stat)</i><br>" +
"If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically set you to start working out at a gym to train a particular stat. If you are " +
"already in the middle of some 'working' action (such as working at a company, for a faction, or on a program), then " +
"running this function will automatically cancel that action and give you your earnings.<br><br>" +
"The first argument must be a string with the name of the gym. The names are NOT case-sensitive. Note that you must " +
"be in the correct city for whatever gym you specify. The available gyms are:<br><br>" +
"Crush Fitness Gym<br>Snap Fitness Gym<br>Iron Gym<br>Powerhouse Gym<br>Millenium Fitness Gym<br><br>" +
"The second argument must be a string with the stat you want to work out. These are NOT case-sensitive. " +
"The valid stats are:<br><br>strength OR str<br>defense OR def<br>dexterity OR dex<br>agility OR agi<br><br>" +
"The cost and experience gains for all of these gyms are the same as if you were to manually visit these gyms and train " +
"This function will return true if you successfully start working out at the gym, and false otherwise.<br><br>" +
"<i>travelToCity(cityname)</i><br>" +
"If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.<br><br>" +
"This function allows the player to travel to any city. The cost for using this function is the same as the cost for traveling through the Travel Agency.<br><br>" +
"The argument passed into this must be a string with the name of the city to travel to. Note that this argument IS CASE SENSITIVE. The valid cities are:<br><br>" +
"Aevum<br>Chongqing<br>Sector-12<br>New Tokyo<br>Ishima<br>Volhaven<br><br>" +
"This function will return true if you successfully travel to the specified city and false otherwise.<br><br>" +
"<i>purchaseTor()</i><br>" +
"If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.<br><br>" +
"This function allows you to automatically purchase a TOR router. The cost for purchasing a TOR router using this " +
"function is the same as if you were to manually purchase one.<br><br>" +
"This function will return true if it successfully purchase a TOR router and false otherwise.<br><br>" +
"<i>purchaseProgram(programName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 1 of Source-File 4 in order to use this function.<br><br>" +
"This function allows you to automatically purchase programs. You MUST have a TOR router in order to use this function.<br><br>" +
"The argument passed in must be a string with the name of the program (including the '.exe' extension). This argument is " +
"NOT case-sensitive.<br><br>Example: " +
"purchaseProgram('brutessh.exe');<br><br>" +
"The cost of purchasing programs using this function is the same as if you were purchasing them through the Dark Web (using " +
"the buy Terminal command).<br><br>" +
"This function will return true if the specified program is purchased, and false otherwise.<br><br>" +
"<i>upgradeHomeRam()</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will upgrade amount of RAM on the player's home computer. The cost is the same as if you were to do it manually.<br><br>" +
"This function will return true if the player's home computer RAM is successfully upgraded, and false otherwise.<br><br>" +
"<i>getUpgradeHomeRamCost()</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"Returns the cost of upgrading the player's home computer RAM.<br><br>" +
"<i>workForCompany()</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically set you to start working at the company at which you are employed. If you are already " +
"in the middle of some 'working' action (such as working for a faction, training at a gym, or creating a program), then " +
"running this function will automatically cancel that action and give you your earnings.<br><br>" +
"This function will return true if the player starts working, and false otherwise.<br><br>" +
"<i>applyToCompany(companyName, field)</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically try to apply to the specified company for a position in the specified field. This " +
"function can also be used to apply for promotions by specifying the company and field you are already employed at.<br><br>" +
"The first argument must be a string with the name of the company. This argument IS CASE-SENSITIVE. The second argument must " +
"be a string representing the 'field' to which you want to apply. This second argument is NOT case-sensitive. Valid values for " +
"the second argument are:<br><br>" +
"software<br>software consultant<br>it<br>security engineer<br>network engineer<br>business<br>business consultant<br>" +
"security<br>agent<br>employee<br>part-time employee<br>waiter<br>part-time waiter<br><br>" +
"This function will return true if you successfully get a job/promotion, and false otherwise. Note " +
"that if you are trying to use this function to apply for a promotion and you don't get one, it will return false.<br><br>" +
"<i>getCompanyRep(companyName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will return the amount of reputation you have at the specified company. If the company passed in as " +
"an argument is invalid, -1 will be returned.<br><br>" +
"The argument passed in must be a string with the name of the company. This argument IS CASE-SENSITIVE.<br><br>" +
"<i>checkFactionInvitations()</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"Returns an array with the name of all Factions you currently have oustanding invitations from.<br><br>" +
"<i>joinFaction(name)</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically accept an invitation from a faction and join it.<br><br>" +
"The argument must be a string with the name of the faction. This name IS CASE-SENSITIVE.<br><br>" +
"<i>workForFaction(factionName, workType)</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically set you to start working for the specified Faction. Obviously, you " +
"must be a member of the Faction or else this function will fail. If you are already in the middle of " +
"some 'working' action (such as working for a company, training at a gym, or creating a program), then running " +
"this function will automatically cancel that action and give you your earnings.<br><br>" +
"The first argument must be a string with the name of the faction. This argument IS CASE-SENSITIVE. The second argument " +
"must be a string with the type of work you want to perform for the faction. The valid values for this argument are:<br><br>" +
"<br>hacking/hacking contracts/hackingcontracts<br>field/fieldwork/field work<br>security/securitywork/security work<br><br>" +
"This function will return true if you successfully start working for the specified faction, and false otherwise.<br><br>" +
"<i>getFactionRep(factionName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 2 of Source-File 4 in order to use this function.<br><br>" +
"This function returns the amount of reputation you have for the specified Faction. The argument must be a " +
"string with the name of the Faction. The argument IS CASE-SENSITIVE.<br><br>" +
"<i>createProgram(programName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically set you to start working on creating the specified program. If you are already in " +
"the middle of some 'working' action (such as working for a company, training at a gym, or taking a course), then " +
"running this function will automatically cancel that action and give you your earnings.<br><br>" +
"The argument passed in must be a string designating the name of the program. This argument is NOT case-sensitive.<br><br>" +
"Example:<br><br>createProgram('relaysmtp.exe');<br><br>" +
"Note that creating a program using this function has the same hacking level requirements as it normally would. These level requirements are:<br><br>" +
"BruteSSH.exe: 50<br>FTPCrack.exe: 100<br>relaySMTP.exe: 250<br>HTTPWorm.exe: 500<br>SQLInject.exe: 750<br>" +
"DeepscanV1.exe: 75<br>DeepscanV2.exe: 400<br>ServerProfiler.exe: 75<br>AutoLink.exe: 25<br><br>" +
"This function returns true if you successfully start working on the specified program, and false otherwise.<br><br>" +
"<i>getAugmentationCost(augName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.<br><br>" +
"This function returns an array with two elements that gives the cost for the specified Augmentation" +
". The first element in the returned array is the reputation requirement of the Augmentation, and the second element " +
"is the money cost.<br><br>" +
"The argument passed in must be a string with the name of the Augmentation. This argument IS CASE-SENSITIVE. " +
"If an invalid Augmentation name is passed in, this function will return the array [-1, -1].<br><br>" +
"<i>purchaseAugmentation(factionName, augName)</i><br>" +
"If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.<br><br>" +
"This function will try to purchase the specified Augmentation through the given Faction.<br><br>" +
"The two arguments must be strings specifying the name of the Faction and Augmentation, respectively. These arguments are both CASE-SENSITIVE.<br><br>" +
"This function will return true if the Augmentation is successfully purchased, and false otherwise.<br><br>" +
"<i>installAugmentations()</i><br>" +
"If you are not in BitNode-4, then you must have Level 3 of Source-File 4 in order to use this function.<br><br>" +
"This function will automatically install your Augmentations, resetting the game as usual.<br><br>" +
"It will return true if successful, and false otherwise.",
TutorialTravelingText:"There are six major cities in the world that you are able to travel to: <br><br> " +
" Aevum<br>" +
" Chongqing<br>" +
" Sector-12<br>" +
" New Tokyo<br>" +
" Ishima<br>" +
" Volhaven<br><br>" +
"To travel between cities, visit your current city's travel agency through the 'World' page. " +
"From the travel agency you can travel to any other city. Doing so costs money. <br><br>" +
"Each city has its own set of companies and unique locations. Also, certain content is only available to you " +
"if you are in certain cities, so get exploring!",
TutorialCompaniesText: "Hacking is not the only way to gain money and experience! Located around the world are many " +
"different companies which you can work for. By working for a company you can earn money, " +
"train your various labor skills, and unlock powerful passive perks. <br><br> " +
"To apply for a job, visit the company you want to work for through the 'World' menu. The company " +
"page will have options that let you apply to positions in the company. There might be several different " +
"positions you can apply for, ranging from software engineer to business analyst to security officer. <br><br> " +
"When you apply for a job, you will get the offer if your stats are high enough. Your first position at " +
"a company will be an entry-level position such as 'intern'. Once you get the job, an button will appear on " +
"the company page that allows you to work for the company. Click this button to start working. <br><br>" +
"Working occurs in 8 hour shifts. Once you start working, you will begin earning money, experience, " +
"and reputation. The rate at which you money and experience depends on the company and your position. " +
"The amount of reputation you gain for your company is based on your job performance, which is affected by " +
"your stats. Different positions value different stats. When you are working, you are unable to perform any " +
"other actions such as using your terminal or visiting other locations (However, note that any scripts you have " +
"running on servers will continue to run as you work!). It is possible to cancel your work shift before the " +
"8 hours is up. However, if you have a full-time job, then cancelling a shift early will result in you gaining " +
"only half of the reputation " +
"that you had earned up to that point. There are also part-time/consultant jobs available where you will not " +
" be penalized if you cancel a work shift early. However, these positions pay less than full-time positions.<br><br>" +
"As you continue to work at a company, you will gain more and more reputation at that company. When your stats " +
"and reputation are high enough, you can get a promotion. You can apply for a promotion on the company page, just like " +
"you applied for the job originally. Higher positions at a company provide better salaries and stat gains.<br><br>" +
"<h1>Infiltrating Companies</h1><br>" +
"Many companies have facilities that you can attempt to infiltrate. By infiltrating, you can steal classified company secrets " +
"and then sell these for money or for faction reputation. To try and infiltrate a company, visit a company through the " +
"'World' menu. There will be an option that says 'Infiltrate Company'. <br><br>" +
"When infiltrating a company, you must progress through clearance levels in the facility. Every clearance level " +
"has some form of security that you must get past. There are several forms of security, ranging from high-tech security systems to " +
"armed guards. For each form of security, there are a variety of options that you can choose to try and bypass the security. Examples " +
"include hacking the security, engaging in combat, assassination, or sneaking past the security. The chance to succeed for each option " +
"is determined in part by your stats. So, for example, trying to hack the security system relies on your hacking skill, whereas trying to " +
"sneak past the security relies on your agility level.<br><br>" +
"The facility has a 'security level' that affects your chance of success when trying to get past a clearance level. " +
"Every time you advance to the next clearance level, the facility's security level will increase by a fixed amount. Furthermore " +
"the options you choose and whether you succeed or fail will affect the security level as well. For example, " +
"if you try to kill a security guard and fail, the security level will increase by a lot. If you choose to sneak past " +
"security and succeed, the security level will not increase at all. <br><br>" +
"Every 5 clearance levels, you will steal classified company secrets that can be sold for money or faction reputation. However, " +
"in order to sell these secrets you must successfully escape the facility using the 'Escape' option. Furthermore, companies have " +
"a max clearance level. If you reach the max clearance level you will automatically escape the facility with all of your " +
"stolen secrets.<br><br>",
TutorialFactionsText: "Throughout the game you may receive invitations from factions. There are many different factions, and each faction " +
"has different criteria for determining its potential members. Joining a faction and furthering its cause is crucial " +
"to progressing in the game and unlocking endgame content. <br><br> " +
"It is possible to join multiple factions if you receive invitations from them. However, note that joining a faction " +
"may prevent you from joining other rival factions. <br><br> " +
"The 'Factions' link on the menu brings up a list of all factions that you have joined. " +
"You can select a Faction on this list to go to that Faction page. This page displays general " +
"information about the Faction and also lets you perform work for the faction. " +
"Working for a Faction is similar to working for a company except that you don't get paid a salary. " +
"You will only earn reputation in your Faction and train your stats. Also, cancelling work early " +
"when working for a Faction does NOT result in reduced experience/reputation earnings. <br><br>" +
"Earning reputation for a Faction unlocks powerful Augmentations. Purchasing and installing these Augmentations will " +
"upgrade your abilities. The Augmentations that are available to unlock vary from faction to faction.",
TutorialAugmentationsText: "Advances in science and medicine have lead to powerful new technologies that allow people to augment themselves " +
"beyond normal human capabilities. There are many different types of Augmentations, ranging from cybernetic to " +
"genetic to biological. Acquiring these Augmentations enhances the user's physical and mental faculties. <br><br>" +
"Because of how powerful these Augmentations are, the technology behind them is kept private and secret by the " +
"corporations and organizations that create them. Therefore, the only way for the player to obtain Augmentations is " +
"through Factions. After joining a Faction and earning enough reputation in it, you will be able to purchase " +
"its Augmentations. Different Factions offer different Augmentations. Augmentations must be purchased in order to be installed, " +
"and they are fairly expensive. <br><br>" +
"When you purchase an Augmentation, the price of purchasing another Augmentation increases by 90%. This multiplier stacks for " +
"each Augmentation you purchase. You will not gain the benefits of your purchased Augmentations until you install them. You can " +
"choose to install Augmentations through the 'Augmentations' menu tab. Once you install your purchased Augmentations, " +
"their costs are reset back to the original price.<br><br>" +
"Unfortunately, installing Augmentations has side effects. You will lose most of the progress you've made, including your " +
"skills, stats, and money. You will have to start over, but you will have all of the Augmentations you have installed to " +
"help you progress. <br><br> " +
"To summarize, here is a list of everything you will LOSE when you install an Augmentation: <br><br>" +
"Stats/Skills<br>" +
"Money<br>" +
"Scripts on all servers EXCEPT your home computer<br>" +
"Purchased servers<br>" +
"Hacknet Nodes<br>" +
"Company/faction reputation<br>" +
"Jobs and Faction memberships<br>" +
"Programs<br>" +
"Stocks<br>" +
"TOR router<br><br>" +
"Here is everything you will KEEP when you install an Augmentation: <br><br>" +
"Every Augmentation you have installed<br>" +
"Scripts on your home computer<br>" +
"RAM Upgrades on your home computer<br>" +
"World Stock Exchange account and TIX API Access<br>",
LatestUpdate:
"v0.28.1<br>" +
"-The script editor now uses the open-source Ace editor, which provides a much better experience when coding!<br>" +
"-Added tprint() Netscript function<br><br>" +
"v0.28.0<br>" +
"-Added BitNode-4: The Singularity<br>" +
"-Added BitNode-11: The Big Crash<br>" +
"-Migrated the codebase to use webpack (doesn't affect any in game content, except maybe some slight " +
"performance improvements and there may be bugs that result from dependency errors)"
}
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__ = __webpack_require__(37);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js__ = __webpack_require__(38);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_LogBox_js__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__ActiveScriptsUI_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Gang_js__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__InteractiveTutorial_js__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__Literature_js__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__Message_js__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__NetscriptFunctions_js__ = __webpack_require__(39);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__Prestige_js__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__RedPill_js__ = __webpack_require__(44);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__SaveObject_js__ = __webpack_require__(58);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__SourceFile_js__ = __webpack_require__(30);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__StockMarket_js__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_31__Terminal_js__ = __webpack_require__(19);
var ace = __webpack_require__(33);
__webpack_require__(35);
__webpack_require__(36);
__webpack_require__(49);
__webpack_require__(50);
/* Shortcuts to navigate through the game
* Alt-t - Terminal
* Alt-c - Character
* Alt-e - Script editor
* Alt-s - Active scripts
* Alt-h - Hacknet Nodes
* Alt-w - City
* Alt-j - Job
* Alt-r - Travel Agency of current city
* Alt-p - Create program
* Alt-f - Factions
* Alt-a - Augmentations
* Alt-u - Tutorial
* Alt-o - Options
*/
$(document).keydown(function(e) {
if (!__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].isWorking && !__WEBPACK_IMPORTED_MODULE_23__RedPill_js__["b" /* redPillFlag */]) {
if (e.keyCode == 84 && e.altKey) {
e.preventDefault();
Engine.loadTerminalContent();
} else if (e.keyCode == 67 && e.altKey) {
e.preventDefault();
Engine.loadCharacterContent();
} else if (e.keyCode == 69 && e.altKey) {
e.preventDefault();
Engine.loadScriptEditorContent();
} else if (e.keyCode == 83 && e.altKey) {
e.preventDefault();
Engine.loadActiveScriptsContent();
} else if (e.keyCode == 72 && e.altKey) {
e.preventDefault();
Engine.loadHacknetNodesContent();
} else if (e.keyCode == 87 && e.altKey) {
e.preventDefault();
Engine.loadWorldContent();
} else if (e.keyCode == 74 && e.altKey) {
e.preventDefault();
Engine.loadJobContent();
} else if (e.keyCode == 82 && e.altKey) {
e.preventDefault();
Engine.loadTravelContent();
} else if (e.keyCode == 80 && e.altKey) {
e.preventDefault();
Engine.loadCreateProgramContent();
} else if (e.keyCode == 70 && e.altKey) {
e.preventDefault();
Engine.loadFactionsContent();
} else if (e.keyCode == 65 && e.altKey) {
e.preventDefault();
Engine.loadAugmentationsContent();
} else if (e.keyCode == 85 && e.altKey) {
e.preventDefault();
Engine.loadTutorialContent();
}
}
if (e.keyCode == 79 && e.altKey) {
e.preventDefault();
Object(__WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__["b" /* gameOptionsBoxOpen */])();
}
});
let Engine = {
version: "",
Debug: true,
//Clickable objects
Clickables: {
//Main menu buttons
terminalMainMenuButton: null,
characterMainMenuButton: null,
scriptEditorMainMenuButton: null,
activeScriptsMainMenuButton: null,
hacknetNodesMainMenuButton: null,
worldMainMenuButton: null,
travelMainMenuButton: null,
jobMainMenuButton: null,
createProgramMainMenuButton: null,
factionsMainMenuButton: null,
augmentationsMainMenuButton: null,
tutorialMainMenuButton: null,
saveMainMenuButton: null,
deleteMainMenuButton: null,
//Tutorial buttons
tutorialNetworkingButton: null,
tutorialHackingButton: null,
tutorialScriptsButton: null,
tutorialNetscriptButton: null,
tutorialTravelingButton: null,
tutorialCompaniesButton: null,
tutorialFactionsButton: null,
tutorialAugmentationsButton: null,
tutorialBackButton: null,
},
//Display objects
Display: {
//Progress bar
progress: null,
//Display for status text (such as "Saved" or "Loaded")
statusText: null,
hacking_skill: null,
//Main menu content
terminalContent: null,
characterContent: null,
scriptEditorContent: null,
activeScriptsContent: null,
hacknetNodesContent: null,
worldContent: null,
createProgramContent: null,
factionsContent: null,
factionContent: null,
factionAugmentationsContent: null,
augmentationsContent: null,
tutorialContent: null,
infiltrationContent: null,
stockMarketContent: null,
locationContent: null,
workInProgressContent: null,
redPillContent: null,
//Character info
characterInfo: null,
},
//Current page status
Page: {
Terminal: "Terminal",
CharacterInfo: "CharacterInfo",
ScriptEditor: "ScriptEditor",
ActiveScripts: "ActiveScripts",
HacknetNodes: "HacknetNodes",
World: "World",
CreateProgram: "CreateProgram",
Factions: "Factions",
Faction: "Faction",
Augmentations: "Augmentations",
Tutorial: "Tutorial",
Location: "Location",
workInProgress: "WorkInProgress",
RedPill: "RedPill",
Infiltration: "Infiltration",
StockMarket: "StockMarket",
Gang: "Gang",
},
currentPage: null,
//Time variables (milliseconds unix epoch time)
_lastUpdate: new Date().getTime(),
_idleSpeed: 200, //Speed (in ms) at which the main loop is updated
/* Load content when a main menu button is clicked */
loadTerminalContent: function() {
Engine.hideAllContent();
Engine.Display.terminalContent.style.visibility = "visible";
Engine.currentPage = Engine.Page.Terminal;
document.getElementById("terminal-menu-link").classList.add("active");
},
loadCharacterContent: function() {
Engine.hideAllContent();
Engine.Display.characterContent.style.visibility = "visible";
Engine.displayCharacterInfo();
Engine.currentPage = Engine.Page.CharacterInfo;
document.getElementById("stats-menu-link").classList.add("active");
},
loadScriptEditorContent: function(filename = "", code = "") {
Engine.hideAllContent();
Engine.Display.scriptEditorContent.style.visibility = "visible";
var editor = ace.edit('javascript-editor');
if (filename != "") {
document.getElementById("script-editor-filename").value = filename;
editor.setValue(code);
}
editor.focus();
Object(__WEBPACK_IMPORTED_MODULE_25__Script_js__["f" /* updateScriptEditorContent */])();
Engine.currentPage = Engine.Page.ScriptEditor;
document.getElementById("create-script-menu-link").classList.add("active");
},
loadActiveScriptsContent: function() {
Engine.hideAllContent();
Engine.Display.activeScriptsContent.style.visibility = "visible";
Object(__WEBPACK_IMPORTED_MODULE_6__ActiveScriptsUI_js__["c" /* setActiveScriptsClickHandlers */])();
Engine.currentPage = Engine.Page.ActiveScripts;
document.getElementById("active-scripts-menu-link").classList.add("active");
},
loadHacknetNodesContent: function() {
Engine.hideAllContent();
Engine.Display.hacknetNodesContent.style.visibility = "visible";
Object(__WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__["a" /* displayHacknetNodesContent */])();
Engine.currentPage = Engine.Page.HacknetNodes;
document.getElementById("hacknet-nodes-menu-link").classList.add("active");
},
loadWorldContent: function() {
Engine.hideAllContent();
Engine.Display.worldContent.style.visibility = "visible";
Engine.displayWorldInfo();
Engine.currentPage = Engine.Page.World;
document.getElementById("city-menu-link").classList.add("active");
},
loadCreateProgramContent: function() {
Engine.hideAllContent();
Engine.Display.createProgramContent.style.visibility = "visible";
Object(__WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__["b" /* displayCreateProgramContent */])();
Engine.currentPage = Engine.Page.CreateProgram;
document.getElementById("create-program-menu-link").classList.add("active");
},
loadFactionsContent: function() {
Engine.hideAllContent();
Engine.Display.factionsContent.style.visibility = "visible";
Engine.displayFactionsInfo();
Engine.currentPage = Engine.Page.Factions;
document.getElementById("factions-menu-link").classList.add("active");
},
loadFactionContent: function() {
Engine.hideAllContent();
Engine.Display.factionContent.style.visibility = "visible";
Engine.currentPage = Engine.Page.Faction;
},
loadAugmentationsContent: function() {
Engine.hideAllContent();
Engine.Display.augmentationsContent.style.visibility = "visible";
Engine.displayAugmentationsContent();
Engine.currentPage = Engine.Page.Augmentations;
document.getElementById("augmentations-menu-link").classList.add("active");
},
loadTutorialContent: function() {
Engine.hideAllContent();
Engine.Display.tutorialContent.style.visibility = "visible";
Engine.displayTutorialContent();
Engine.currentPage = Engine.Page.Tutorial;
document.getElementById("tutorial-menu-link").classList.add("active");
},
loadLocationContent: function() {
Engine.hideAllContent();
Engine.Display.locationContent.style.visibility = "visible";
Object(__WEBPACK_IMPORTED_MODULE_13__Location_js__["b" /* displayLocationContent */])();
Engine.currentPage = Engine.Page.Location;
},
loadTravelContent: function() {
switch(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].city) {
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Aevum:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].AevumTravelAgency;
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Chongqing:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].ChongqingTravelAgency;
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Sector12:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Sector12TravelAgency;
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].NewTokyo:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].NewTokyoTravelAgency;
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Ishima:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].IshimaTravelAgency;
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Volhaven:
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].VolhavenTravelAgency;
break;
default:
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: Invalid city. This is a bug please contact game dev");
break;
}
Engine.loadLocationContent();
},
loadJobContent: function() {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].companyName == "") {
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not currently have a job! You can visit various companies " +
"in the city and try to find a job.");
return;
}
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].location = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].companyName;
Engine.loadLocationContent();
},
loadWorkInProgressContent: function() {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.visibility = "visible";
Engine.currentPage = Engine.Page.WorkInProgress;
},
loadRedPillContent: function() {
Engine.hideAllContent();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "hidden";
Engine.Display.redPillContent.style.visibility = "visible";
Engine.currentPage = Engine.Page.RedPill;
},
loadInfiltrationContent: function() {
Engine.hideAllContent();
Engine.Display.infiltrationContent.style.visibility = "visible";
Engine.currentPage = Engine.Page.Infiltration;
},
loadStockMarketContent: function() {
Engine.hideAllContent();
Engine.Display.stockMarketContent.style.visibility = "visible";
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["c" /* displayStockMarketContent */])();
Engine.currentPage = Engine.Page.StockMarket;
},
loadGangContent: function() {
Engine.hideAllContent();
if (document.getElementById("gang-container") || __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].inGang()) {
Object(__WEBPACK_IMPORTED_MODULE_14__Gang_js__["c" /* displayGangContent */])();
Engine.currentPage = Engine.Page.Gang;
} else {
Engine.loadTerminalContent();
Engine.currentPage = Engine.Page.Terminal;
}
},
//Helper function that hides all content
hideAllContent: function() {
Engine.Display.terminalContent.style.visibility = "hidden";
Engine.Display.characterContent.style.visibility = "hidden";
Engine.Display.scriptEditorContent.style.visibility = "hidden";
Engine.Display.activeScriptsContent.style.visibility = "hidden";
Engine.Display.hacknetNodesContent.style.visibility = "hidden";
Engine.Display.worldContent.style.visibility = "hidden";
Engine.Display.createProgramContent.style.visibility = "hidden";
Engine.Display.factionsContent.style.visibility = "hidden";
Engine.Display.factionContent.style.visibility = "hidden";
Engine.Display.factionAugmentationsContent.style.visibility = "hidden";
Engine.Display.augmentationsContent.style.visibility = "hidden";
Engine.Display.tutorialContent.style.visibility = "hidden";
Engine.Display.locationContent.style.visibility = "hidden";
Engine.Display.workInProgressContent.style.visibility = "hidden";
Engine.Display.redPillContent.style.visibility = "hidden";
Engine.Display.infiltrationContent.style.visibility = "hidden";
Engine.Display.stockMarketContent.style.visibility = "hidden";
if (document.getElementById("gang-container")) {
document.getElementById("gang-container").style.visibility = "hidden";
}
//Location lists
Engine.aevumLocationsList.style.display = "none";
Engine.chongqingLocationsList.style.display = "none";
Engine.sector12LocationsList.style.display = "none";
Engine.newTokyoLocationsList.style.display = "none";
Engine.ishimaLocationsList.style.display = "none";
Engine.volhavenLocationsList.style.display = "none";
//Make nav menu tabs inactive
document.getElementById("terminal-menu-link").classList.remove("active");
document.getElementById("create-script-menu-link").classList.remove("active");
document.getElementById("active-scripts-menu-link").classList.remove("active");
document.getElementById("create-program-menu-link").classList.remove("active");
document.getElementById("stats-menu-link").classList.remove("active");
document.getElementById("factions-menu-link").classList.remove("active");
document.getElementById("augmentations-menu-link").classList.remove("active");
document.getElementById("hacknet-nodes-menu-link").classList.remove("active");
document.getElementById("city-menu-link").classList.remove("active");
document.getElementById("tutorial-menu-link").classList.remove("active");
document.getElementById("options-menu-link").classList.remove("active");
},
displayCharacterOverviewInfo: function() {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hp == null) {__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hp = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].max_hp;}
document.getElementById("character-overview-text").innerHTML =
("Hp: " + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hp + " / " + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].max_hp + "<br>" +
"Money: " + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].money.toNumber()).format('($0.000a)') + "<br>" +
"Hack: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_skill).toLocaleString() + "<br>" +
"Str: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].strength).toLocaleString() + "<br>" +
"Def: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].defense).toLocaleString() + "<br>" +
"Dex: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].dexterity).toLocaleString() + "<br>" +
"Agi: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].agility).toLocaleString() + "<br>" +
"Cha: " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].charisma).toLocaleString()
).replace( / /g, "&nbsp;" );
},
/* Display character info */
displayCharacterInfo: function() {
var companyPosition = "";
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].companyPosition != "") {
companyPosition = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].companyPosition.positionName;
}
Engine.Display.characterInfo.innerHTML =
('<b>General</b><br><br>' +
'Current City: ' + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].city + '<br><br>' +
'Employer: ' + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].companyName + '<br>' +
'Job Title: ' + companyPosition + '<br><br>' +
'Money: $' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].money.toNumber(), 2)+ '<br><br><br>' +
'<b>Stats</b><br><br>' +
'Hacking Level: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_skill).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_exp).format('(0.000a)') + ' experience)<br>' +
'Strength: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].strength).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].strength_exp).format('(0.000a)') + ' experience)<br>' +
'Defense: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].defense).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].defense_exp).format('(0.000a)')+ ' experience)<br>' +
'Dexterity: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].dexterity).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].dexterity_exp).format('(0.000a)') + ' experience)<br>' +
'Agility: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].agility).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].agility_exp).format('(0.000a)') + ' experience)<br>' +
'Charisma: ' + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].charisma).toLocaleString() +
" (" + __WEBPACK_IMPORTED_MODULE_3__utils_numeral_min_js___default()(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].charisma_exp).format('(0.000a)') + ' experience)<br><br><br>' +
'<b>Multipliers</b><br><br>' +
'Hacking Chance multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_chance_mult * 100, 2) + '%<br>' +
'Hacking Speed multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_speed_mult * 100, 2) + '%<br>' +
'Hacking Money multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_money_mult * 100, 2) + '%<br>' +
'Hacking Growth multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_grow_mult * 100, 2) + '%<br><br>' +
'Hacking Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_mult * 100, 2) + '%<br>' +
'Hacking Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacking_exp_mult * 100, 2) + '%<br><br>' +
'Strength Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].strength_mult * 100, 2) + '%<br>' +
'Strength Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].strength_exp_mult * 100, 2) + '%<br><br>' +
'Defense Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].defense_mult * 100, 2) + '%<br>' +
'Defense Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].defense_exp_mult * 100, 2) + '%<br><br>' +
'Dexterity Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].dexterity_mult * 100, 2) + '%<br>' +
'Dexterity Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].dexterity_exp_mult * 100, 2) + '%<br><br>' +
'Agility Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].agility_mult * 100, 2) + '%<br>' +
'Agility Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].agility_exp_mult * 100, 2) + '%<br><br>' +
'Charisma Level multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].charisma_mult * 100, 2) + '%<br>' +
'Charisma Experience multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].charisma_exp_mult * 100, 2) + '%<br><br>' +
'Hacknet Node production multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknet_node_money_mult * 100, 2) + '%<br>' +
'Hacknet Node purchase cost multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node RAM upgrade cost multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node Core purchase cost multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknet_node_core_cost_mult * 100, 2) + '%<br>' +
'Hacknet Node level upgrade cost multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknet_node_level_cost_mult * 100, 2) + '%<br><br>' +
'Company reputation gain multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].company_rep_mult * 100, 2) + '%<br>' +
'Faction reputation gain multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].faction_rep_mult * 100, 2) + '%<br>' +
'Salary multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].work_money_mult * 100, 2) + '%<br>' +
'Crime success multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].crime_success_mult * 100, 2) + '%<br>' +
'Crime money multiplier: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].crime_money_mult * 100, 2) + '%<br><br><br>' +
'<b>Misc</b><br><br>' +
'Servers owned: ' + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].purchasedServers.length + '<br>' +
'Hacknet Nodes owned: ' + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hacknetNodes.length + '<br>' +
'Augmentations installed: ' + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].augmentations.length + '<br>' +
'Time played since last Augmentation: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug) + '<br>' +
'Time played: ' + Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["b" /* convertTimeMsToTimeElapsedString */])(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime) + '<br><br><br>').replace( / /g, "&nbsp;" );
},
/* Display locations in the world*/
aevumLocationsList: null,
chongqingLocationsList: null,
sector12LocationsList: null,
newTokyoLocationsList: null,
ishimaLocationsList: null,
volhavenLocationsList: null,
displayWorldInfo: function() {
Engine.aevumLocationsList.style.display = "none";
Engine.chongqingLocationsList.style.display = "none";
Engine.sector12LocationsList.style.display = "none";
Engine.newTokyoLocationsList.style.display = "none";
Engine.ishimaLocationsList.style.display = "none";
Engine.volhavenLocationsList.style.display = "none";
document.getElementById("world-city-name").innerHTML = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].city;
var cityDesc = document.getElementById("world-city-desc"); //TODO
switch(__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].city) {
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Aevum:
Engine.aevumLocationsList.style.display = "inline";
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Chongqing:
Engine.chongqingLocationsList.style.display = "inline";
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Sector12:
Engine.sector12LocationsList.style.display = "inline";
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].NewTokyo:
Engine.newTokyoLocationsList.style.display = "inline";
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Ishima:
Engine.ishimaLocationsList.style.display = "inline";
break;
case __WEBPACK_IMPORTED_MODULE_13__Location_js__["a" /* Locations */].Volhaven:
Engine.volhavenLocationsList.style.display = "inline";
break;
default:
console.log("Invalid city value in Player object!");
break;
}
document.getElementById("generic-locations-list").style.display = "inline";
},
displayFactionsInfo: function() {
//Clear the list of joined factions
var factionsList = document.getElementById("factions-list");
while (factionsList.firstChild) {
factionsList.removeChild(factionsList.firstChild);
}
//Re-add a link for each faction you are a member of
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factions.length; ++i) {
(function () {
var factionName = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factions[i];
//Add the faction to the Factions page content
var item = document.createElement("li");
var aElem = document.createElement("a");
aElem.setAttribute("class", "a-link-button");
aElem.innerHTML = factionName;
aElem.addEventListener("click", function() {
Engine.loadFactionContent();
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["c" /* displayFactionContent */])(factionName);
return false;
});
item.appendChild(aElem);
factionsList.appendChild(item);
}()); //Immediate invocation
}
//Clear the list of invitations
var invitationsList = document.getElementById("outstanding-faction-invitations-list");
while (invitationsList.firstChild) {
invitationsList.removeChild(invitationsList.firstChild);
}
//Add a link to accept for each faction you have invitiations for
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factionInvitations.length; ++i) {
(function () {
var factionName = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factionInvitations[i];
var item = document.createElement("li");
var pElem = document.createElement("p");
pElem.innerText = factionName;
pElem.style.display = "inline";
pElem.style.margin = "4px";
pElem.style.padding = "4px";
var aElem = document.createElement("a");
aElem.innerText = "Accept Faction Invitation";
aElem.setAttribute("class", "a-link-button");
aElem.style.display = "inline";
aElem.style.margin = "4px";
aElem.style.padding = "4px";
aElem.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["h" /* joinFaction */])(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["b" /* Factions */][factionName]);
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factionInvitations.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factionInvitations[i] == factionName) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].factionInvitations.splice(i, 1);
break;
}
}
Engine.displayFactionsInfo();
return false;
});
item.appendChild(pElem);
item.appendChild(aElem);
item.style.margin = "6px";
item.style.padding = "6px";
invitationsList.appendChild(item);
}());
}
},
displayAugmentationsContent: function() {
//Purchased/queued augmentations
var queuedAugmentationsList = document.getElementById("queued-augmentations-list");
while (queuedAugmentationsList.firstChild) {
queuedAugmentationsList.removeChild(queuedAugmentationsList.firstChild);
}
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].queuedAugmentations.length; ++i) {
var augName = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].queuedAugmentations[i].name;
var aug = __WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["c" /* Augmentations */][augName];
var item = document.createElement("li");
var hElem = document.createElement("h2");
var pElem = document.createElement("p");
item.setAttribute("class", "installed-augmentation");
hElem.innerHTML = augName;
if (augName == __WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
hElem.innerHTML += " - Level " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].queuedAugmentations[i].level);
}
pElem.innerHTML = aug.info;
item.appendChild(hElem);
item.appendChild(pElem);
queuedAugmentationsList.appendChild(item);
}
//Install Augmentations button
var installButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("install-augmentations-button");
installButton.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["h" /* installAugmentations */])();
return false;
});
//Installed augmentations
var augmentationsList = document.getElementById("augmentations-list");
while (augmentationsList.firstChild) {
augmentationsList.removeChild(augmentationsList.firstChild);
}
//Source Files - Temporary...Will probably put in a separate pane Later
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].sourceFiles.length; ++i) {
var srcFileKey = "SourceFile" + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].sourceFiles[i].n;
var sourceFileObject = __WEBPACK_IMPORTED_MODULE_28__SourceFile_js__["b" /* SourceFiles */][srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].sourceFiles[i].n);
continue;
}
var item = document.createElement("li");
var hElem = document.createElement("h2");
var pElem = document.createElement("p");
item.setAttribute("class", "installed-augmentation");
hElem.innerHTML = sourceFileObject.name + "<br>";
hElem.innerHTML += "Level " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].sourceFiles[i].lvl) + " / 3";
pElem.innerHTML = sourceFileObject.info;
item.appendChild(hElem);
item.appendChild(pElem);
augmentationsList.appendChild(item);
}
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].augmentations.length; ++i) {
var augName = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].augmentations[i].name;
var aug = __WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["c" /* Augmentations */][augName];
var item = document.createElement("li");
var hElem = document.createElement("h2");
var pElem = document.createElement("p");
item.setAttribute("class", "installed-augmentation");
hElem.innerHTML = augName;
if (augName == __WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
hElem.innerHTML += " - Level " + (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].augmentations[i].level);
}
pElem.innerHTML = aug.info;
item.appendChild(hElem);
item.appendChild(pElem);
augmentationsList.appendChild(item);
}
},
displayTutorialContent: function() {
document.getElementById("tutorial-getting-started-link").style.display = "block";
Engine.Clickables.tutorialNetworkingButton.style.display = "block";
Engine.Clickables.tutorialHackingButton.style.display = "block";
Engine.Clickables.tutorialScriptsButton.style.display = "block";
Engine.Clickables.tutorialNetscriptButton.style.display = "block";
Engine.Clickables.tutorialTravelingButton.style.display = "block";
Engine.Clickables.tutorialCompaniesButton.style.display = "block";
Engine.Clickables.tutorialFactionsButton.style.display = "block";
Engine.Clickables.tutorialAugmentationsButton.style.display = "block";
document.getElementById("tutorial-shortcuts-link").style.display = "block";
Engine.Clickables.tutorialBackButton.style.display = "none";
document.getElementById("tutorial-text").style.display = "none";
},
//Displays the text when a section of the Tutorial is opened
displayTutorialPage: function(text) {
document.getElementById("tutorial-getting-started-link").style.display = "none";
Engine.Clickables.tutorialNetworkingButton.style.display = "none";
Engine.Clickables.tutorialHackingButton.style.display = "none";
Engine.Clickables.tutorialScriptsButton.style.display = "none";
Engine.Clickables.tutorialNetscriptButton.style.display = "none";
Engine.Clickables.tutorialTravelingButton.style.display = "none";
Engine.Clickables.tutorialCompaniesButton.style.display = "none";
Engine.Clickables.tutorialFactionsButton.style.display = "none";
Engine.Clickables.tutorialAugmentationsButton.style.display = "none";
document.getElementById("tutorial-shortcuts-link").style.display = "none";
Engine.Clickables.tutorialBackButton.style.display = "inline-block";
document.getElementById("tutorial-text").style.display = "block";
document.getElementById("tutorial-text").innerHTML = text;
},
/* Main Event Loop */
idleTimer: function() {
//Get time difference
var _thisUpdate = new Date().getTime();
var diff = _thisUpdate - Engine._lastUpdate;
var offset = diff % Engine._idleSpeed;
//Divide this by cycle time to determine how many cycles have elapsed since last update
diff = Math.floor(diff / Engine._idleSpeed);
if (diff > 0) {
//Update the game engine by the calculated number of cycles
Engine._lastUpdate = _thisUpdate - offset;
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].lastUpdate = _thisUpdate - offset;
Engine.updateGame(diff);
}
window.requestAnimationFrame(Engine.idleTimer);
},
updateGame: function(numCycles = 1) {
//Update total playtime
var time = numCycles * Engine._idleSpeed;
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime == null) {__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime = 0;}
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug == null) {__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug = 0;}
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime += time;
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug += time;
//Start Manual hack
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].startAction == true) {
Engine._totalActionTime = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].actionTime;
Engine._actionTimeLeft = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].actionTime;
Engine._actionInProgress = true;
Engine._actionProgressBarCount = 1;
Engine._actionProgressStr = "[ ]";
Engine._actionTimeStr = "Time left: ";
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].startAction = false;
}
//Working
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].isWorking) {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workForFaction(numCycles);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCreateProgram) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].createProgramWork(numCycles);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].takeClass(numCycles);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCrime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].commitCrime(numCycles);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCompanyPartTime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workPartTime(numCycles);
} else {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].work(numCycles);
}
}
//Gang, if applicable
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].inGang()) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].gang.process(numCycles);
}
//Counters
Engine.decrementAllCounters(numCycles);
Engine.checkCounters();
//Manual hacks
if (Engine._actionInProgress == true) {
Engine.updateHackProgress(numCycles);
}
//Update the running time of all active scripts
Object(__WEBPACK_IMPORTED_MODULE_20__NetscriptWorker_js__["g" /* updateOnlineScriptTimes */])(numCycles);
//Hacknet Nodes
Object(__WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__["c" /* processAllHacknetNodeEarnings */])(numCycles);
},
//Counters for the main event loop. Represent the number of game cycles are required
//for something to happen.
Counters: {
autoSaveCounter: 300, //Autosave every minute
updateSkillLevelsCounter: 10, //Only update skill levels every 2 seconds. Might improve performance
updateDisplays: 3, //Update displays such as Active Scripts display and character display
updateDisplaysMed: 9,
updateDisplaysLong: 15,
createProgramNotifications: 10, //Checks whether any programs can be created and notifies
checkFactionInvitations: 100, //Check whether you qualify for any faction invitations
passiveFactionGrowth: 600,
messages: 150,
stockTick: 30, //Update stock prices
sCr: 1500,
updateScriptEditorDisplay: 5,
},
decrementAllCounters: function(numCycles = 1) {
for (var counter in Engine.Counters) {
if (Engine.Counters.hasOwnProperty(counter)) {
Engine.Counters[counter] = Engine.Counters[counter] - numCycles;
}
}
},
//Checks if any counters are 0 and if they are, executes whatever
//is necessary and then resets the counter
checkCounters: function() {
if (Engine.Counters.autoSaveCounter <= 0) {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].saveGame();
Engine.Counters.autoSaveCounter = 300;
}
if (Engine.Counters.updateSkillLevelsCounter <= 0) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].updateSkillLevels();
Engine.Counters.updateSkillLevelsCounter = 10;
}
if (Engine.Counters.updateDisplays <= 0) {
Engine.displayCharacterOverviewInfo();
if (Engine.currentPage == Engine.Page.CharacterInfo) {
Engine.displayCharacterInfo();
} else if (Engine.currentPage == Engine.Page.HacknetNodes) {
Object(__WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__["e" /* updateHacknetNodesContent */])();
} else if (Engine.currentPage == Engine.Page.CreateProgram) {
Object(__WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__["b" /* displayCreateProgramContent */])();
}
if (__WEBPACK_IMPORTED_MODULE_5__utils_LogBox_js__["b" /* logBoxOpened */]) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_LogBox_js__["c" /* logBoxUpdateText */])();
}
Engine.Counters.updateDisplays = 3;
}
if (Engine.Counters.updateDisplaysMed <= 0) {
if (Engine.currentPage == Engine.Page.ActiveScripts) {
Object(__WEBPACK_IMPORTED_MODULE_6__ActiveScriptsUI_js__["d" /* updateActiveScriptsItems */])();
}
Engine.Counters.updateDisplaysMed = 9;
}
if (Engine.Counters.updateDisplaysLong <= 0) {
if (Engine.currentPage === Engine.Page.Gang) {
Object(__WEBPACK_IMPORTED_MODULE_14__Gang_js__["e" /* updateGangContent */])();
}
Engine.Counters.updateDisplaysLong = 15;
}
if (Engine.Counters.createProgramNotifications <= 0) {
var num = Object(__WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__["c" /* getNumAvailableCreateProgram */])();
var elem = document.getElementById("create-program-notification");
if (num > 0) {
elem.innerHTML = num;
elem.setAttribute("class", "notification-on");
} else {
elem.innerHTML = "";
elem.setAttribute("class", "notification-off");
}
Engine.Counters.createProgramNotifications = 10;
}
if (Engine.Counters.checkFactionInvitations <= 0) {
var invitedFactions = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].checkForFactionInvitations();
if (invitedFactions.length > 0) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].firstFacInvRecvd = true;
var randFaction = invitedFactions[Math.floor(Math.random() * invitedFactions.length)];
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["g" /* inviteToFaction */])(randFaction);
}
Engine.Counters.checkFactionInvitations = 100;
}
if (Engine.Counters.passiveFactionGrowth <= 0) {
var adjustedCycles = Math.floor((600 - Engine.Counters.passiveFactionGrowth));
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["j" /* processPassiveFactionRepGain */])(adjustedCycles);
Engine.Counters.passiveFactionGrowth = 600;
}
if (Engine.Counters.messages <= 0) {
Object(__WEBPACK_IMPORTED_MODULE_18__Message_js__["c" /* checkForMessagesToSend */])();
Engine.Counters.messages = 150;
}
if (Engine.Counters.stockTick <= 0) {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hasWseAccount) {
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["k" /* updateStockPrices */])();
}
Engine.Counters.stockTick = 30;
}
if (Engine.Counters.sCr <= 0) {
//Assume 4Sig will always indicate state of market
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hasWseAccount) {
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["i" /* stockMarketCycle */])();
}
Engine.Counters.sCr = 1500;
}
if (Engine.Counters.updateScriptEditorDisplay <= 0) {
if (Engine.currentPage == Engine.Page.ScriptEditor) {
Object(__WEBPACK_IMPORTED_MODULE_25__Script_js__["f" /* updateScriptEditorContent */])();
}
Engine.Counters.updateScriptEditorDisplay = 5;
}
},
/* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */
_totalActionTime: 0,
_actionTimeLeft: 0,
_actionTimeStr: "Time left: ",
_actionProgressStr: "[ ]",
_actionProgressBarCount: 1,
_actionInProgress: false,
updateHackProgress: function(numCycles = 1) {
var timeElapsedMilli = numCycles * Engine._idleSpeed;
Engine._actionTimeLeft -= (timeElapsedMilli/ 1000); //Substract idle speed (ms)
Engine._actionTimeLeft = Math.max(Engine._actionTimeLeft, 0);
//Calculate percent filled
var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100);
//Update progress bar
while (Engine._actionProgressBarCount * 2 <= percent) {
Engine._actionProgressStr = Engine._actionProgressStr.replaceAt(Engine._actionProgressBarCount, "|");
Engine._actionProgressBarCount += 1;
}
//Update hack time remaining
Engine._actionTimeStr = "Time left: " + Math.max(0, Math.round(Engine._actionTimeLeft)).toString() + "s";
document.getElementById("hack-progress").innerHTML = Engine._actionTimeStr;
//Dynamically update progress bar
document.getElementById("hack-progress-bar").innerHTML = Engine._actionProgressStr.replace( / /g, "&nbsp;" );
//Once percent is 100, the hack is completed
if (percent >= 100) {
Engine._actionInProgress = false;
__WEBPACK_IMPORTED_MODULE_31__Terminal_js__["a" /* Terminal */].finishAction();
}
},
_prevTimeout: null,
createStatusText: function(txt) {
if (Engine._prevTimeout != null) {
clearTimeout(Engine._prevTimeout);
Engine._prevTimeout = null;
}
var statusText = document.getElementById("status-text")
statusText.style.display = "inline-block";
statusText.setAttribute("class", "status-text");
statusText.innerHTML = txt;
Engine._prevTimeout = setTimeout(function() {
statusText.style.display = "none";
statusText.removeAttribute("class");
statusText.innerHTML = "";
}, 3000);
},
removeLoadingScreen: function() {
var loader = document.getElementById("loader");
if (!loader) {return;}
while(loader.firstChild) {
loader.removeChild(loader.firstChild);
}
loader.parentNode.removeChild(loader);
document.getElementById("entire-game-container").style.visibility = "visible";
},
load: function() {
//Load script editor
var editor = ace.edit('javascript-editor');
editor.getSession().setMode('ace/mode/javascript');
editor.setTheme('ace/theme/monokai');
document.getElementById('javascript-editor').style.fontSize='16px';
editor.setOption("showPrintMargin", false);
//Initialize main menu accordion panels to all start as "open"
var terminal = document.getElementById("terminal-tab");
var createScript = document.getElementById("create-script-tab");
var activeScripts = document.getElementById("active-scripts-tab");
var createProgram = document.getElementById("create-program-tab");
var stats = document.getElementById("stats-tab");
var factions = document.getElementById("factions-tab");
var augmentations = document.getElementById("augmentations-tab");
var hacknetnodes = document.getElementById("hacknet-nodes-tab");
var city = document.getElementById("city-tab");
var travel = document.getElementById("travel-tab");
var job = document.getElementById("job-tab");
var tutorial = document.getElementById("tutorial-tab");
var options = document.getElementById("options-tab");
//Load game from save or create new game
if (Object(__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["a" /* loadGame */])(__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */])) {
console.log("Loaded game from save");
Object(__WEBPACK_IMPORTED_MODULE_8__BitNode_js__["d" /* initBitNodes */])();
Object(__WEBPACK_IMPORTED_MODULE_8__BitNode_js__["c" /* initBitNodeMultipliers */])();
Object(__WEBPACK_IMPORTED_MODULE_28__SourceFile_js__["d" /* initSourceFiles */])();
Engine.setDisplayElements(); //Sets variables for important DOM elements
Engine.init(); //Initialize buttons, work, etc.
__WEBPACK_IMPORTED_MODULE_9__Company_js__["d" /* CompanyPositions */].init();
Object(__WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["g" /* initAugmentations */])(); //Also calls Player.reapplyAllAugmentations()
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].reapplyAllSourceFiles();
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["e" /* initStockSymbols */])();
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].hasWseAccount) {
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["f" /* initSymbolToStockMap */])();
}
Object(__WEBPACK_IMPORTED_MODULE_17__Literature_js__["a" /* initLiterature */])();
Object(__WEBPACK_IMPORTED_MODULE_19__NetscriptFunctions_js__["c" /* initSingularitySFFlags */])();
//Calculate the number of cycles have elapsed while offline
Engine._lastUpdate = new Date().getTime();
var lastUpdate = __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].lastUpdate;
var numCyclesOffline = Math.floor((Engine._lastUpdate - lastUpdate) / Engine._idleSpeed);
/* Process offline progress */
var offlineProductionFromScripts = Object(__WEBPACK_IMPORTED_MODULE_25__Script_js__["e" /* loadAllRunningScripts */])(); //This also takes care of offline production for those scripts
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].isWorking) {
console.log("work() called in load() for " + numCyclesOffline * Engine._idleSpeed + " milliseconds");
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workForFaction(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCreateProgram) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].createProgramWork(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].takeClass(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCrime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].commitCrime(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCompanyPartTime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workPartTime(numCyclesOffline);
} else {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].work(numCyclesOffline);
}
}
//Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(__WEBPACK_IMPORTED_MODULE_15__HacknetNode_js__["c" /* processAllHacknetNodeEarnings */])(numCyclesOffline);
//Passive faction rep gain offline
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["j" /* processPassiveFactionRepGain */])(numCyclesOffline);
//Gang progress for BitNode 2
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].bitNodeN != null && __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].inGang()) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].gang.process(numCyclesOffline);
}
//Update total playtime
var time = numCyclesOffline * Engine._idleSpeed;
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime == null) {__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime = 0;}
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug == null) {__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug = 0;}
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].totalPlaytime += time;
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].playtimeSinceLastAug += time;
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].lastUpdate = Engine._lastUpdate;
Engine.start(); //Run main game loop and Scripts loop
Engine.removeLoadingScreen();
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])("While you were offline, your scripts generated $" +
Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineProductionFromScripts, 2) + " and your Hacknet Nodes generated $" +
Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineProductionFromHacknetNodes, 2));
//Close main menu accordions for loaded game
terminal.style.maxHeight = null;
terminal.style.opacity = 0;
terminal.style.pointerEvents = "none";
createScript.style.maxHeight = null;
createScript.style.opacity = 0;
createScript.style.pointerEvents = "none";
activeScripts.style.maxHeight = null;
activeScripts.style.opacity = 0;
activeScripts.style.pointerEvents = "none";
createProgram.style.maxHeight = null;
createProgram.style.opacity = 0;
createProgram.style.pointerEvents = "none";
stats.style.maxHeight = null;
stats.style.opacity = 0;
stats.style.pointerEvents = "none";
factions.style.maxHeight = null;
factions.style.opacity = 0;
factions.style.pointerEvents = "none";
augmentations.style.maxHeight = null;
augmentations.style.opacity = 0;
augmentations.style.pointerEvents = "none";
hacknetnodes.style.maxHeight = null;
hacknetnodes.style.opacity = 0;
hacknetnodes.style.pointerEvents = "none";
city.style.maxHeight = null;
city.style.opacity = 0;
city.style.pointerEvents = "none";
travel.style.maxHeight = null;
travel.style.opacity = 0;
travel.style.pointerEvents = "none";
job.style.maxHeight = null;
job.style.opacity = 0;
job.style.pointerEvents = "none";
tutorial.style.maxHeight = null;
tutorial.style.opacity = 0;
tutorial.style.pointerEvents = "none";
options.style.maxHeight = null;
options.style.opacity = 0;
options.style.pointerEvents = "none";
} else {
//No save found, start new game
console.log("Initializing new game");
Object(__WEBPACK_IMPORTED_MODULE_8__BitNode_js__["d" /* initBitNodes */])();
Object(__WEBPACK_IMPORTED_MODULE_8__BitNode_js__["c" /* initBitNodeMultipliers */])();
Object(__WEBPACK_IMPORTED_MODULE_28__SourceFile_js__["d" /* initSourceFiles */])();
Object(__WEBPACK_IMPORTED_MODULE_29__SpecialServerIps_js__["c" /* initSpecialServerIps */])();
Engine.setDisplayElements(); //Sets variables for important DOM elements
Engine.start(); //Run main game loop and Scripts loop
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].init();
Object(__WEBPACK_IMPORTED_MODULE_26__Server_js__["f" /* initForeignServers */])();
Object(__WEBPACK_IMPORTED_MODULE_9__Company_js__["h" /* initCompanies */])();
Object(__WEBPACK_IMPORTED_MODULE_12__Faction_js__["f" /* initFactions */])();
__WEBPACK_IMPORTED_MODULE_9__Company_js__["d" /* CompanyPositions */].init();
Object(__WEBPACK_IMPORTED_MODULE_7__Augmentations_js__["g" /* initAugmentations */])();
Object(__WEBPACK_IMPORTED_MODULE_18__Message_js__["d" /* initMessages */])();
Object(__WEBPACK_IMPORTED_MODULE_30__StockMarket_js__["e" /* initStockSymbols */])();
Object(__WEBPACK_IMPORTED_MODULE_17__Literature_js__["a" /* initLiterature */])();
Object(__WEBPACK_IMPORTED_MODULE_19__NetscriptFunctions_js__["c" /* initSingularitySFFlags */])();
//Open main menu accordions for new game
//Main menu accordions
var hackingHdr = document.getElementById("hacking-menu-header");
hackingHdr.classList.toggle("opened");
var characterHdr = document.getElementById("character-menu-header");
characterHdr.classList.toggle("opened");
var worldHdr = document.getElementById("world-menu-header");
worldHdr.classList.toggle("opened");
var helpHdr = document.getElementById("help-menu-header");
helpHdr.classList.toggle("opened");
terminal.style.maxHeight = terminal.scrollHeight + "px";
terminal.style.display = "block";
createScript.style.maxHeight = createScript.scrollHeight + "px";
createScript.style.display = "block";
activeScripts.style.maxHeight = activeScripts.scrollHeight + "px";
activeScripts.style.display = "block";
createProgram.style.maxHeight = createProgram.scrollHeight + "px";
createProgram.style.display = "block";
stats.style.maxHeight = stats.scrollHeight + "px";
stats.style.display = "block";
factions.style.maxHeight = factions.scrollHeight + "px";
factions.style.display = "block";
augmentations.style.maxHeight = augmentations.scrollHeight + "px";
augmentations.style.display = "block";
hacknetnodes.style.maxHeight = hacknetnodes.scrollHeight + "px";
hacknetnodes.style.display = "block";
city.style.maxHeight = city.scrollHeight + "px";
city.style.display = "block";
travel.style.maxHeight = travel.scrollHeight + "px";
travel.style.display = "block";
job.style.maxHeight = job.scrollHeight + "px";
job.style.display = "block";
tutorial.style.maxHeight = tutorial.scrollHeight + "px";
tutorial.style.display = "block";
options.style.maxHeight = options.scrollHeight + "px";
options.style.display = "block";
//Start interactive tutorial
Object(__WEBPACK_IMPORTED_MODULE_16__InteractiveTutorial_js__["d" /* iTutorialStart */])();
Engine.removeLoadingScreen();
}
//Initialize labels on game settings
Object(__WEBPACK_IMPORTED_MODULE_27__Settings_js__["d" /* setSettingsLabels */])();
},
setDisplayElements: function() {
//Content elements
Engine.Display.terminalContent = document.getElementById("terminal-container");
Engine.currentPage = Engine.Page.Terminal;
Engine.Display.characterContent = document.getElementById("character-container");
Engine.Display.characterContent.style.visibility = "hidden";
Engine.Display.scriptEditorContent = document.getElementById("script-editor-container");
Engine.Display.scriptEditorContent.style.visibility = "hidden";
Engine.Display.activeScriptsContent = document.getElementById("active-scripts-container");
Engine.Display.activeScriptsContent.style.visibility = "hidden";
Engine.Display.hacknetNodesContent = document.getElementById("hacknet-nodes-container");
Engine.Display.hacknetNodesContent.style.visibility = "hidden";
Engine.Display.worldContent = document.getElementById("world-container");
Engine.Display.worldContent.style.visibility = "hidden";
Engine.Display.createProgramContent = document.getElementById("create-program-container");
Engine.Display.createProgramContent.style.visibility = "hidden";
Engine.Display.factionsContent = document.getElementById("factions-container");
Engine.Display.factionsContent.style.visibility = "hidden";
Engine.Display.factionContent = document.getElementById("faction-container");
Engine.Display.factionContent.style.visibility = "hidden";
Engine.Display.factionAugmentationsContent = document.getElementById("faction-augmentations-container");
Engine.Display.factionAugmentationsContent.style.visibility = "hidden";
Engine.Display.augmentationsContent = document.getElementById("augmentations-container");
Engine.Display.augmentationsContent.style.visibility = "hidden";
Engine.Display.tutorialContent = document.getElementById("tutorial-container");
Engine.Display.tutorialContent.style.visibility = "hidden";
Engine.Display.infiltrationContent = document.getElementById("infiltration-container");
Engine.Display.infiltrationContent.style.visibility = "hidden";
Engine.Display.stockMarketContent = document.getElementById("stock-market-container");
Engine.Display.stockMarketContent.style.visibility = "hidden";
//Character info
Engine.Display.characterInfo = document.getElementById("character-info");
//Location lists
Engine.aevumLocationsList = document.getElementById("aevum-locations-list");
Engine.chongqingLocationsList = document.getElementById("chongqing-locations-list");
Engine.sector12LocationsList = document.getElementById("sector12-locations-list");
Engine.newTokyoLocationsList = document.getElementById("newtokyo-locations-list");
Engine.ishimaLocationsList = document.getElementById("ishima-locations-list");
Engine.volhavenLocationsList = document.getElementById("volhaven-locations-list");
//Location page (page that shows up when you visit a specific location in World)
Engine.Display.locationContent = document.getElementById("location-container");
Engine.Display.locationContent.style.visibility = "hidden";
//Work In Progress
Engine.Display.workInProgressContent = document.getElementById("work-in-progress-container");
Engine.Display.workInProgressContent.style.visibility = "hidden";
//Red Pill / Hack World Daemon
Engine.Display.redPillContent = document.getElementById("red-pill-container");
Engine.Display.redPillContent.style.visibility = "hidden";
//Init Location buttons
Object(__WEBPACK_IMPORTED_MODULE_13__Location_js__["c" /* initLocationButtons */])();
//Tutorial buttons
Engine.Clickables.tutorialNetworkingButton = document.getElementById("tutorial-networking-link");
Engine.Clickables.tutorialNetworkingButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialNetworkingText);
});
Engine.Clickables.tutorialHackingButton = document.getElementById("tutorial-hacking-link");
Engine.Clickables.tutorialHackingButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialHackingText);
});
Engine.Clickables.tutorialScriptsButton = document.getElementById("tutorial-scripts-link");
Engine.Clickables.tutorialScriptsButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialScriptsText);
});
Engine.Clickables.tutorialNetscriptButton = document.getElementById("tutorial-netscript-link");
Engine.Clickables.tutorialNetscriptButton.addEventListener("click", function() {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].bitNodeN === 4 || __WEBPACK_IMPORTED_MODULE_19__NetscriptFunctions_js__["b" /* hasSingularitySF */]) {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialNetscriptText + __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialSingularityFunctionsText);
} else {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialNetscriptText);
}
});
Engine.Clickables.tutorialTravelingButton = document.getElementById("tutorial-traveling-link");
Engine.Clickables.tutorialTravelingButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialTravelingText);
});
Engine.Clickables.tutorialCompaniesButton = document.getElementById("tutorial-jobs-link");
Engine.Clickables.tutorialCompaniesButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialCompaniesText);
});
Engine.Clickables.tutorialFactionsButton = document.getElementById("tutorial-factions-link");
Engine.Clickables.tutorialFactionsButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialFactionsText);
});
Engine.Clickables.tutorialAugmentationsButton = document.getElementById("tutorial-augmentations-link");
Engine.Clickables.tutorialAugmentationsButton.addEventListener("click", function() {
Engine.displayTutorialPage(__WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].TutorialAugmentationsText);
});
Engine.Clickables.tutorialBackButton = document.getElementById("tutorial-back-button");
Engine.Clickables.tutorialBackButton.addEventListener("click", function() {
Engine.displayTutorialContent();
});
//If DarkWeb already purchased, disable the button
if (__WEBPACK_IMPORTED_MODULE_29__SpecialServerIps_js__["a" /* SpecialServerIps */].hasOwnProperty("Darkweb Server")) {
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive");
}
},
/* Initialization */
init: function() {
//Import game link
document.getElementById("import-game-link").onclick = function() {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].importGame();
};
//Main menu accordions
var hackingHdr = document.getElementById("hacking-menu-header");
//hackingHdr.classList.toggle("opened");
var characterHdr = document.getElementById("character-menu-header");
//characterHdr.classList.toggle("opened");
var worldHdr = document.getElementById("world-menu-header");
//worldHdr.classList.toggle("opened");
var helpHdr = document.getElementById("help-menu-header");
//helpHdr.classList.toggle("opened");
hackingHdr.onclick = function() {
var terminal = document.getElementById("terminal-tab");
var terminalLink = document.getElementById("terminal-menu-link");
var createScript = document.getElementById("create-script-tab");
var createScriptLink = document.getElementById("create-script-menu-link");
var activeScripts = document.getElementById("active-scripts-tab");
var activeScriptsLink = document.getElementById("active-scripts-menu-link");
var createProgram = document.getElementById("create-program-tab");
var createProgramLink = document.getElementById("create-program-menu-link");
var createProgramNot = document.getElementById("create-program-notification");
this.classList.toggle("opened");
if (terminal.style.maxHeight) {
terminal.style.opacity = 0;
terminal.style.maxHeight = null;
terminalLink.style.opacity = 0;
terminalLink.style.maxHeight = null;
terminalLink.style.pointerEvents = "none";
createScript.style.opacity = 0;
createScript.style.maxHeight = null;
createScriptLink.style.opacity = 0;
createScriptLink.style.maxHeight = null;
createScriptLink.style.pointerEvents = "none";
activeScripts.style.opacity = 0;
activeScripts.style.maxHeight = null;
activeScriptsLink.style.opacity = 0;
activeScriptsLink.style.maxHeight = null;
activeScriptsLink.style.pointerEvents = "none";
createProgram.style.opacity = 0;
createProgram.style.maxHeight = null;
createProgramLink.style.opacity = 0;
createProgramLink.style.maxHeight = null;
createProgramLink.style.pointerEvents = "none";
createProgramNot.style.display = "none";
} else {
terminal.style.maxHeight = terminal.scrollHeight + "px";
terminal.style.opacity = 1;
terminalLink.style.maxHeight = terminalLink.scrollHeight + "px";
terminalLink.style.opacity = 1;
terminalLink.style.pointerEvents = "auto";
createScript.style.maxHeight = createScript.scrollHeight + "px";
createScript.style.opacity = 1;
createScriptLink.style.maxHeight = createScriptLink.scrollHeight + "px";
createScriptLink.style.opacity = 1;
createScriptLink.style.pointerEvents = "auto";
activeScripts.style.maxHeight = activeScripts.scrollHeight + "px";
activeScripts.style.opacity = 1;
activeScriptsLink.style.maxHeight = activeScriptsLink.scrollHeight + "px";
activeScriptsLink.style.opacity = 1;
activeScriptsLink.style.pointerEvents = "auto";
createProgram.style.maxHeight = createProgram.scrollHeight + "px";
createProgram.style.opacity = 1;
createProgramLink.style.maxHeight = createProgramLink.scrollHeight + "px";
createProgramLink.style.opacity = 1;
createProgramLink.style.pointerEvents = "auto";
createProgramNot.style.display = "block"
}
}
characterHdr.onclick = function() {
var stats = document.getElementById("stats-tab");
var statsLink = document.getElementById("stats-menu-link");
var factions = document.getElementById("factions-tab");
var factionsLink = document.getElementById("factions-menu-link");
var augmentations = document.getElementById("augmentations-tab");
var augmentationsLink = document.getElementById("augmentations-menu-link");
var hacknetnodes = document.getElementById("hacknet-nodes-tab");
var hacknetnodesLink = document.getElementById("hacknet-nodes-menu-link");
this.classList.toggle("opened");
if (stats.style.maxHeight) {
stats.style.opacity = 0;
stats.style.maxHeight = null;
statsLink.style.opacity = 0;
statsLink.style.maxHeight = null;
statsLink.style.pointerEvents = "none";
factions.style.opacity = 0;
factions.style.maxHeight = null;
factionsLink.style.opacity = 0;
factionsLink.style.maxHeight = null;
factionsLink.style.pointerEvents = "none";
augmentations.style.opacity = 0;
augmentations.style.maxHeight = null;
augmentationsLink.style.opacity = 0;
augmentationsLink.style.maxHeight = null;
augmentationsLink.style.pointerEvents = "none";
hacknetnodes.style.opacity = 0;
hacknetnodes.style.maxHeight = null;
hacknetnodesLink.style.opacity = 0;
hacknetnodesLink.style.maxHeight = null;
hacknetnodesLink.style.pointerEvents = "none";
} else {
stats.style.maxHeight = stats.scrollHeight + "px";
stats.style.opacity = 1;
statsLink.style.maxHeight = statsLink.scrollHeight + "px";
statsLink.style.opacity = 1;
statsLink.style.pointerEvents = "auto";
factions.style.maxHeight = factions.scrollHeight + "px";
factions.style.opacity = 1;
factionsLink.style.maxHeight = factionsLink.scrollHeight + "px";
factionsLink.style.opacity = 1;
factionsLink.style.pointerEvents = "auto";
augmentations.style.maxHeight = augmentations.scrollHeight + "px";
augmentations.style.opacity = 1;
augmentationsLink.style.maxHeight = augmentationsLink.scrollHeight + "px";
augmentationsLink.style.opacity = 1;
augmentationsLink.style.pointerEvents = "auto";
hacknetnodes.style.maxHeight = hacknetnodes.scrollHeight + "px";
hacknetnodes.style.opacity = 1;
hacknetnodesLink.style.maxHeight = hacknetnodesLink.scrollHeight + "px";
hacknetnodesLink.style.opacity = 1;
hacknetnodesLink.style.pointerEvents = "auto";
}
}
worldHdr.onclick = function() {
var city = document.getElementById("city-tab");
var cityLink = document.getElementById("city-menu-link");
var travel = document.getElementById("travel-tab");
var travelLink = document.getElementById("travel-menu-link");
var job = document.getElementById("job-tab");
var jobLink = document.getElementById("job-menu-link");
this.classList.toggle("opened");
if (city.style.maxHeight) {
city.style.opacity = 0;
city.style.maxHeight = null;
cityLink.style.opacity = 0;
cityLink.style.maxHeight = null;
cityLink.style.pointerEvents = "none";
travel.style.opacity = 0;
travel.style.maxHeight = null;
travelLink.style.opacity = 0;
travelLink.style.maxHeight = null;
travelLink.style.pointerEvents = "none";
job.style.opacity = 0;
job.style.maxHeight = null;
jobLink.style.opacity = 0;
jobLink.style.maxHeight = null;
jobLink.style.pointerEvents = "none";
} else {
city.style.maxHeight = city.scrollHeight + "px";
city.style.opacity = 1;
cityLink.style.maxHeight = cityLink.scrollHeight + "px";
cityLink.style.opacity = 1;
cityLink.style.pointerEvents = "auto";
travel.style.maxHeight = travel.scrollHeight + "px";
travel.style.opacity = 1;
travelLink.style.maxHeight = travelLink.scrollHeight + "px";
travelLink.style.opacity = 1;
travelLink.style.pointerEvents = "auto";
job.style.maxHeight = job.scrollHeight + "px";
job.style.opacity = 1;
jobLink.style.maxHeight = jobLink.scrollHeight + "px";
jobLink.style.opacity = 1;
jobLink.style.pointerEvents = "auto";
}
}
helpHdr.onclick = function() {
var tutorial = document.getElementById("tutorial-tab");
var tutorialLink = document.getElementById("tutorial-menu-link");
var options = document.getElementById("options-tab");
var optionsLink = document.getElementById("options-menu-link");
this.classList.toggle("opened");
if (tutorial.style.maxHeight) {
tutorial.style.opacity = 0;
tutorial.style.maxHeight = null;
tutorialLink.style.opacity = 0;
tutorialLink.style.maxHeight = null;
tutorialLink.style.pointerEvents = "none";
options.style.opacity = 0;
options.style.maxHeight = null;
optionsLink.style.opacity = 0;
optionsLink.style.maxHeight = null;
optionsLink.style.pointerEvents = "none";
} else {
tutorial.style.maxHeight = tutorial.scrollHeight + "px";
tutorial.style.opacity = 1;
tutorialLink.style.maxHeight = tutorialLink.scrollHeight + "px";
tutorialLink.style.opacity = 1;
tutorialLink.style.pointerEvents = "auto";
options.style.maxHeight = options.scrollHeight + "px";
options.style.opacity = 1;
optionsLink.style.maxHeight = optionsLink.scrollHeight + "px";
optionsLink.style.opacity = 1;
optionsLink.style.pointerEvents = "auto";
}
}
//Main menu buttons and content
Engine.Clickables.terminalMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link");
Engine.Clickables.terminalMainMenuButton.addEventListener("click", function() {
Engine.loadTerminalContent();
return false;
});
Engine.Clickables.characterMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stats-menu-link");
Engine.Clickables.characterMainMenuButton.addEventListener("click", function() {
Engine.loadCharacterContent();
return false;
});
Engine.Clickables.scriptEditorMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("create-script-menu-link");
Engine.Clickables.scriptEditorMainMenuButton.addEventListener("click", function() {
Engine.loadScriptEditorContent();
return false;
});
Engine.Clickables.activeScriptsMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("active-scripts-menu-link");
Engine.Clickables.activeScriptsMainMenuButton.addEventListener("click", function() {
Engine.loadActiveScriptsContent();
return false;
});
Engine.Clickables.hacknetNodesMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link");
Engine.Clickables.hacknetNodesMainMenuButton.addEventListener("click", function() {
Engine.loadHacknetNodesContent();
return false;
});
Engine.Clickables.worldMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link");
Engine.Clickables.worldMainMenuButton.addEventListener("click", function() {
Engine.loadWorldContent();
return false;
});
Engine.Clickables.travelMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("travel-menu-link");
Engine.Clickables.travelMainMenuButton.addEventListener("click", function() {
Engine.loadTravelContent();
return false;
});
Engine.Clickables.jobMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("job-menu-link");
Engine.Clickables.jobMainMenuButton.addEventListener("click", function() {
Engine.loadJobContent();
return false;
});
Engine.Clickables.createProgramMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("create-program-menu-link");
Engine.Clickables.createProgramMainMenuButton.addEventListener("click", function() {
Engine.loadCreateProgramContent();
return false;
});
Engine.Clickables.factionsMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("factions-menu-link");
Engine.Clickables.factionsMainMenuButton.addEventListener("click", function() {
Engine.loadFactionsContent();
return false;
});
Engine.Clickables.augmentationsMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("augmentations-menu-link");
Engine.Clickables.augmentationsMainMenuButton.addEventListener("click", function() {
Engine.loadAugmentationsContent();
return false;
});
Engine.Clickables.tutorialMainMenuButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link");
Engine.Clickables.tutorialMainMenuButton.addEventListener("click", function() {
Engine.loadTutorialContent();
return false;
});
//Active scripts list
Engine.ActiveScriptsList = document.getElementById("active-scripts-list");
//Save, Delete, Import/Export buttons
Engine.Clickables.saveMainMenuButton = document.getElementById("save-game-link");
Engine.Clickables.saveMainMenuButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].saveGame();
return false;
});
Engine.Clickables.deleteMainMenuButton = document.getElementById("delete-game-link");
Engine.Clickables.deleteMainMenuButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].deleteGame();
return false;
});
document.getElementById("export-game-link").addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].exportGame();
return false;
});
//Character Overview buttons
document.getElementById("character-overview-save-button").addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_24__SaveObject_js__["b" /* saveObject */].saveGame();
return false;
});
document.getElementById("character-overview-options-button").addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__["b" /* gameOptionsBoxOpen */])();
return false;
});
//Create Program buttons
Object(__WEBPACK_IMPORTED_MODULE_11__CreateProgram_js__["d" /* initCreateProgramButtons */])();
//Message at the top of terminal
Object(__WEBPACK_IMPORTED_MODULE_31__Terminal_js__["c" /* postNetburnerText */])();
//Player was working cancel button
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].isWorking) {
var cancelButton = document.getElementById("work-in-progress-cancel-button");
cancelButton.addEventListener("click", function() {
if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction) {
var fac = __WEBPACK_IMPORTED_MODULE_12__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].currentWorkFactionName];
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishFactionWork(true);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCreateProgram) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishCreateProgramWork(true);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishClass();
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCrime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishCrime(true);
} else if (__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_10__Constants_js__["a" /* CONSTANTS */].WorkTypeCompanyPartTime) {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishWorkPartTime();
} else {
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].finishWork(true);
}
});
Engine.loadWorkInProgressContent();
}
//character overview screen
document.getElementById("character-overview-container").style.display = "block";
//Remove classes from links (they might be set from tutorial)
document.getElementById("terminal-menu-link").removeAttribute("class");
document.getElementById("stats-menu-link").removeAttribute("class");
document.getElementById("create-script-menu-link").removeAttribute("class");
document.getElementById("active-scripts-menu-link").removeAttribute("class");
document.getElementById("hacknet-nodes-menu-link").removeAttribute("class");
document.getElementById("city-menu-link").removeAttribute("class");
document.getElementById("tutorial-menu-link").removeAttribute("class");
//DEBUG Delete active Scripts on home
document.getElementById("debug-delete-scripts-link").addEventListener("click", function() {
console.log("Deleting running scripts on home computer");
__WEBPACK_IMPORTED_MODULE_21__Player_js__["a" /* Player */].getHomeComputer().runningScripts = [];
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Forcefully deleted all running scripts on home computer. Please save and refresh page");
Object(__WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__["a" /* gameOptionsBoxClose */])();
return false;
});
//DEBUG Soft Reset
document.getElementById("debug-soft-reset").addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Soft Reset!");
Object(__WEBPACK_IMPORTED_MODULE_22__Prestige_js__["a" /* prestigeAugmentation */])();
Object(__WEBPACK_IMPORTED_MODULE_1__utils_GameOptions_js__["a" /* gameOptionsBoxClose */])();
return false;
});
},
start: function() {
//Run main loop
Engine.idleTimer();
//Scripts
Object(__WEBPACK_IMPORTED_MODULE_20__NetscriptWorker_js__["f" /* runScriptsLoop */])();
}
};
window.onload = function() {
Engine.load();
};
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export getIndicesOf */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return convertTimeMsToTimeElapsedString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return longestCommonStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isPositiveNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return containsAllStrings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return formatNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return numOccurrences; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return numNetscriptOperators; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__DialogBox_js__ = __webpack_require__(2);
//Netburner String helper functions
//Searches for every occurence of searchStr within str and returns an array of the indices of
//all these occurences
function getIndicesOf(searchStr, str, caseSensitive) {
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
//Replaces the character at an index with a new character
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
//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) {
//Convert ms to seconds, since we only have second-level precision
time = Math.floor(time / 1000);
var days = Math.floor(time / 86400);
time %= 86400;
var hours = Math.floor(time / 3600);
time %= 3600;
var minutes = Math.floor(time / 60);
time %= 60;
var seconds = time;
var res = "";
if (days) {res += days + " days ";}
if (hours) {res += hours + " hours ";}
if (minutes) {res += minutes + " minutes ";}
res += seconds + " seconds ";
return res;
}
//Finds the longest common starting substring in a set of strings
function longestCommonStart(strings) {
if (!containsAllStrings(strings)) {return;}
if (strings.length == 0) {return;}
var A = strings.concat().sort(),
a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;
while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;
return a1.substring(0, i);
}
//Returns whether a variable is a string
function isString(str) {
return (typeof str === 'string' || str instanceof String);
}
//Returns true if string contains only digits (meaning it would be a positive number)
function isPositiveNumber(str) {
return /^\d+$/.test(str);
}
//Returns whether an array contains entirely of string objects
function containsAllStrings(arr) {
return arr.every(isString);
}
//Formats a number with commas and a specific number of decimal digits
function formatNumber(num, numFractionDigits) {
return num.toLocaleString(undefined, {
minimumFractionDigits: numFractionDigits,
maximumFractionDigits: numFractionDigits
});
}
//Count the number of times a substring occurs in a string
function numOccurrences(string, subString) {
string += "";
subString += "";
if (subString.length <= 0) return (string.length + 1);
var n = 0, pos = 0, step = subString.length;
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
++n;
pos += step;
} else break;
}
return n;
}
//Counters the number of Netscript operators in a string
function numNetscriptOperators(string) {
var total = 0;
total += numOccurrences(string, "+");
total += numOccurrences(string, "-");
total += numOccurrences(string, "*");
total += numOccurrences(string, "/");
total += numOccurrences(string, "%");
total += numOccurrences(string, "&&");
total += numOccurrences(string, "||");
total += numOccurrences(string, "<");
total += numOccurrences(string, ">");
total += numOccurrences(string, "<=");
total += numOccurrences(string, ">=");
total += numOccurrences(string, "==");
total += numOccurrences(string, "!=");
if (isNaN(total)) {
Object(__WEBPACK_IMPORTED_MODULE_0__DialogBox_js__["a" /* dialogBoxCreate */])("ERROR in counting number of operators in script. This is a bug, please report to game developer");
total = 0;
}
return total;
}
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return Server; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return GetServerByHostname; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return loadAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AddToAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return processSingleServerGrowth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return initForeignServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return prestigeAllServers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return prestigeHomeComputer; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(7);
function Server(ip=Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), hostname="", organizationName="",
isConnectedTo=false, adminRights=false, purchasedByPlayer=false, maxRam=0) {
/* Properties */
//Connection information
this.ip = ip;
var i = 0;
while (GetServerByHostname(hostname) != null) {
//Server already exists
hostname = hostname + "-" + i;
++i;
}
this.hostname = hostname;
this.organizationName = organizationName;
this.isConnectedTo = isConnectedTo; //Whether the player is connected to this server
//Access information
this.hasAdminRights = adminRights; //Whether player has admin rights
this.purchasedByPlayer = purchasedByPlayer;
this.manuallyHacked = false; //Flag that tracks whether or not the server has been hacked at least once
//RAM, CPU speed and Scripts
this.maxRam = maxRam; //GB
this.ramUsed = 0;
this.cpuSpeed = 1; //MHz
this.scripts = [];
this.runningScripts = []; //Stores RunningScript objects
this.programs = [];
this.messages = [];
/* Hacking information (only valid for "foreign" aka non-purchased servers) */
//Skill required to attempt a hack. Whether a hack is successful will be determined
//by a separate formula
this.requiredHackingSkill = 1;
//Total money available on this server
this.moneyAvailable = 0;
this.moneyMax = 0;
//Parameters used in formulas that dictate how moneyAvailable and requiredHackingSkill change.
this.hackDifficulty = 1; //Affects hack success rate and how the requiredHackingSkill increases over time (1-100)
this.baseDifficulty = 1; //Starting difficulty
this.minDifficulty = 1;
this.serverGrowth = 0; //Affects how the moneyAvailable increases (0-100)
this.timesHacked = 0;
//The IP's of all servers reachable from this one (what shows up if you run scan/netstat)
// NOTE: Only contains IP and not the Server objects themselves
this.serversOnNetwork = [];
//Port information, required for porthacking servers to get admin rights
this.numOpenPortsRequired = 5;
this.sshPortOpen = false; //Port 22
this.ftpPortOpen = false; //Port 21
this.smtpPortOpen = false; //Port 25
this.httpPortOpen = false; //Port 80
this.sqlPortOpen = false; //Port 1433
this.openPortCount = 0;
};
//Set the hacking properties of a server
Server.prototype.setHackingParameters = function(requiredHackingSkill, moneyAvailable, hackDifficulty, serverGrowth) {
this.requiredHackingSkill = requiredHackingSkill;
if (isNaN(moneyAvailable)) {
this.moneyAvailable = 1000000;
} else {
this.moneyAvailable = moneyAvailable * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ServerStartingMoney;
}
this.moneyMax = 25 * this.moneyAvailable * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ServerMaxMoney;
this.hackDifficulty = hackDifficulty;
this.baseDifficulty = hackDifficulty;
this.minDifficulty = Math.max(1, Math.round(hackDifficulty / 3));
this.serverGrowth = serverGrowth;
}
//Set the port properties of a server
//Right now its only the number of open ports needed to PortHack the server.
Server.prototype.setPortProperties = function(numOpenPortsReq) {
this.numOpenPortsRequired = numOpenPortsReq;
}
Server.prototype.setMaxRam = function(ram) {
this.maxRam = ram;
}
//The serverOnNetwork array holds the IP of all the servers. This function
//returns the actual Server objects
Server.prototype.getServerOnNetwork = function(i) {
if (i > this.serversOnNetwork.length) {
console.log("Tried to get server on network that was out of range");
return;
}
return AllServers[this.serversOnNetwork[i]];
}
//Given the name of the script, returns the corresponding
//script object on the server (if it exists)
Server.prototype.getScript = function(scriptName) {
for (var i = 0; i < this.scripts.length; i++) {
if (this.scripts[i].filename == scriptName) {
return this.scripts[i];
}
}
return null;
}
//Strengthens a server's security level (difficulty) by the specified amount
Server.prototype.fortify = function(amt) {
this.hackDifficulty += amt;
if (this.hackDifficulty > 99) {this.hackDifficulty = 99;}
}
Server.prototype.weaken = function(amt) {
this.hackDifficulty -= (amt * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ServerWeakenRate);
if (this.hackDifficulty < this.minDifficulty) {this.hackDifficulty = this.minDifficulty;}
if (this.hackDifficulty < 1) {this.hackDifficulty = 1;}
}
//Functions for loading and saving a Server
Server.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Server", this);
}
Server.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Server, value.data);
}
__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.Server = Server;
function initForeignServers() {
//MegaCorporations
var ECorpServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "ecorp", "ECorp", false, false, false, 0);
ECorpServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1150, 1300), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(30000000000, 70000000000), 99, 99);
ECorpServer.setPortProperties(5);
AddToAllServers(ECorpServer);
var MegaCorpServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "megacorp", "MegaCorp", false, false, false, 0);
MegaCorpServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1150, 1300), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40000000000, 60000000000), 99, 99);
MegaCorpServer.setPortProperties(5);
AddToAllServers(MegaCorpServer);
var BachmanAndAssociatesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "b-and-a", "Bachman & Associates", false, false, false, 0);
BachmanAndAssociatesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1050), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000000000, 25000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 85), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(65, 75));
BachmanAndAssociatesServer.setPortProperties(5);
AddToAllServers(BachmanAndAssociatesServer);
var BladeIndustriesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "blade", "Blade Industries", false, false, false, 0);
BladeIndustriesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1100), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(12000000000, 20000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(90, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 75));
BladeIndustriesServer.setPortProperties(5);
BladeIndustriesServer.messages.push("beyond-man.lit");
AddToAllServers(BladeIndustriesServer);
var NWOServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "nwo", "New World Order", false, false, false, 0);
NWOServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1200), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(25000000000, 35000000000), 99, Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 85));
NWOServer.setPortProperties(5);
NWOServer.messages.push("the-hidden-world.lit");
AddToAllServers(NWOServer);
var ClarkeIncorporatedServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "clarkeinc", "Clarke Incorporated", false, false, false, 0);
ClarkeIncorporatedServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1200), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000000000, 25000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 60), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 70));
ClarkeIncorporatedServer.setPortProperties(5);
ClarkeIncorporatedServer.messages.push("beyond-man.lit");
ClarkeIncorporatedServer.messages.push("cost-of-immortality.lit");
AddToAllServers(ClarkeIncorporatedServer);
var OmniTekIncorporatedServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "omnitek", "OmniTek Incorporated", false, false, false, 0);
OmniTekIncorporatedServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900, 1100), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000000000, 20000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(90, 99), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(95, 99));
OmniTekIncorporatedServer.setPortProperties(5);
OmniTekIncorporatedServer.messages.push("coded-intelligence.lit");
AddToAllServers(OmniTekIncorporatedServer);
var FourSigmaServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "4sigma", "FourSigma", false, false, false, 0);
FourSigmaServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(950, 1200), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000000000, 25000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 70), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 99));
FourSigmaServer.setPortProperties(5);
AddToAllServers(FourSigmaServer);
var KuaiGongInternationalServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "kuai-gong", "KuaiGong International", false, false, false, 0);
KuaiGongInternationalServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1250), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000000000, 30000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(95, 99), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(90, 99));
KuaiGongInternationalServer.setPortProperties(5);
AddToAllServers(KuaiGongInternationalServer);
//Technology and communications companies (large targets)
var FulcrumTechnologiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "fulcrumtech", "Fulcrum Technologies", false, false, false, 64);
FulcrumTechnologiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1200), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1400000000, 1800000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 99));
FulcrumTechnologiesServer.setPortProperties(5);
FulcrumTechnologiesServer.messages.push("simulated-reality.lit");
AddToAllServers(FulcrumTechnologiesServer);
var FulcrumSecretTechnologiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "fulcrumassets", "Fulcrum Technologies Assets", false, false, false, 0);
FulcrumSecretTechnologiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1200, 1500), 1000000, 99, 1);
FulcrumSecretTechnologiesServer.setPortProperties(5);
AddToAllServers(FulcrumSecretTechnologiesServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].FulcrumSecretTechnologies, FulcrumSecretTechnologiesServer.ip);
var StormTechnologiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "stormtech", "Storm Technologies", false, false, false, 0);
StormTechnologiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900, 1050), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000000000, 1200000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 90));
StormTechnologiesServer.setPortProperties(5);
AddToAllServers(StormTechnologiesServer);
var DefCommServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "defcomm", "DefComm", false, false, false, 0);
DefCommServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900, 1000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800000000, 950000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 70));
DefCommServer.setPortProperties(5);
AddToAllServers(DefCommServer);
var InfoCommServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "infocomm", "InfoComm", false, false, false, 0);
InfoCommServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(875, 950), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(600000000, 900000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 75));
InfoCommServer.setPortProperties(5);
AddToAllServers(InfoCommServer);
var HeliosLabsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "helios", "Helios Labs", false, false, false, 0);
HeliosLabsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 900), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(550000000, 750000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80));
HeliosLabsServer.setPortProperties(5);
HeliosLabsServer.messages.push("beyond-man.lit");
AddToAllServers(HeliosLabsServer);
var VitaLifeServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "vitalife", "VitaLife", false, false, false, 32);
VitaLifeServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(775, 900), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(700000000, 800000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80));
VitaLifeServer.setPortProperties(5);
VitaLifeServer.messages.push("A-Green-Tomorrow.lit");
AddToAllServers(VitaLifeServer);
var IcarusMicrosystemsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "icarus", "Icarus Microsystems", false, false, false, 0);
IcarusMicrosystemsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(850, 925), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900000000, 1000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95));
IcarusMicrosystemsServer.setPortProperties(5);
AddToAllServers(IcarusMicrosystemsServer);
var UniversalEnergyServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "univ-energy", "Universal Energy", false, false, false, 32);
UniversalEnergyServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 900), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1100000000, 1200000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90));
UniversalEnergyServer.setPortProperties(4);
AddToAllServers(UniversalEnergyServer);
var TitanLabsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "titan-labs", "Titan Laboratories", false, false, false, 32);
TitanLabsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 875), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(750000000, 900000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80));
TitanLabsServer.setPortProperties(5);
TitanLabsServer.messages.push("coded-intelligence.lit");
AddToAllServers(TitanLabsServer);
var MicrodyneTechnologiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "microdyne", "Microdyne Technologies", false, false, false, 16);
MicrodyneTechnologiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 875), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(500000000, 700000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(65, 75), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 90));
MicrodyneTechnologiesServer.setPortProperties(5);
MicrodyneTechnologiesServer.messages.push("synthetic-muscles.lit");
AddToAllServers(MicrodyneTechnologiesServer);
var TaiYangDigitalServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "taiyang-digital", "Taiyang Digital", false, false, false, 0);
TaiYangDigitalServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(850, 950), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800000000, 900000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80));
TaiYangDigitalServer.setPortProperties(5);
TaiYangDigitalServer.messages.push("A-Green-Tomorrow.lit");
TaiYangDigitalServer.messages.push("brighter-than-the-sun.lit");
AddToAllServers(TaiYangDigitalServer);
var GalacticCyberSystemsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "galactic-cyber", "Galactic Cybersystems", false, false, false, 0);
GalacticCyberSystemsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(825, 875), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(750000000, 850000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 90));
GalacticCyberSystemsServer.setPortProperties(5);
AddToAllServers(GalacticCyberSystemsServer);
//Defense Companies ("Large" Companies)
var AeroCorpServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "aerocorp", "AeroCorp", false, false, false, 0);
AeroCorpServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(850, 925), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000000000, 1200000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65));
AeroCorpServer.setPortProperties(5);
AeroCorpServer.messages.push("man-and-machine.lit");
AddToAllServers(AeroCorpServer);
var OmniaCybersystemsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "omnia", "Omnia Cybersystems", false, false, false, 0);
OmniaCybersystemsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(850, 950), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900000000, 1000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(85, 95), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 70));
OmniaCybersystemsServer.setPortProperties(5);
AddToAllServers(OmniaCybersystemsServer);
var ZBDefenseServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "zb-def", "ZB Defense Industries", false, false, false, 0);
ZBDefenseServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(775, 825), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(900000000, 1100000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(65, 75));
ZBDefenseServer.setPortProperties(4);
ZBDefenseServer.messages.push("synthetic-muscles.lit");
AddToAllServers(ZBDefenseServer);
var AppliedEnergeticsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "applied-energetics", "Applied Energetics", false, false, false, 0);
AppliedEnergeticsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(775, 850), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(700000000, 1000000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 75));
AppliedEnergeticsServer.setPortProperties(4);
AddToAllServers(AppliedEnergeticsServer);
var SolarisSpaceSystemsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "solaris", "Solaris Space Systems", false, false, false, 0);
SolarisSpaceSystemsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(750, 850), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(700000000, 900000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80));
SolarisSpaceSystemsServer.setPortProperties(5);
SolarisSpaceSystemsServer.messages.push("A-Green-Tomorrow.lit");
SolarisSpaceSystemsServer.messages.push("the-failed-frontier.lit");
AddToAllServers(SolarisSpaceSystemsServer);
var DeltaOneServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "deltaone", "Delta One", false, false, false, 0);
DeltaOneServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 900), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1300000000, 1700000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 85), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 70));
DeltaOneServer.setPortProperties(5);
AddToAllServers(DeltaOneServer);
//Health, medicine, pharmaceutical companies ("Large" targets)
var GlobalPharmaceuticalsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "global-pharm", "Global Pharmaceuticals", false, false, false, 16);
GlobalPharmaceuticalsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(750, 850), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1500000000, 1750000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 85), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(80, 90));
GlobalPharmaceuticalsServer.setPortProperties(4);
GlobalPharmaceuticalsServer.messages.push("A-Green-Tomorrow.lit");
AddToAllServers(GlobalPharmaceuticalsServer);
var NovaMedicalServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "nova-med", "Nova Medical", false, false, false, 0);
NovaMedicalServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(775, 850), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1100000000, 1250000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(65, 85));
NovaMedicalServer.setPortProperties(4);
AddToAllServers(NovaMedicalServer);
var ZeusMedicalServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "zeus-med", "Zeus Medical", false, false, false, 0);
ZeusMedicalServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800, 850), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1300000000, 1500000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 90), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80));
ZeusMedicalServer.setPortProperties(5);
AddToAllServers(ZeusMedicalServer);
var UnitaLifeGroupServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "unitalife", "UnitaLife Group", false, false, false, 32);
UnitaLifeGroupServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(775, 825), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000000000, 1100000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80));
UnitaLifeGroupServer.setPortProperties(4);
AddToAllServers(UnitaLifeGroupServer);
//"Medium level" targets
var LexoCorpServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "lexo-corp", "Lexo Corporation", false, false, false, 16);
LexoCorpServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(650, 750), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(700000000, 800000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65));
LexoCorpServer.setPortProperties(4);
AddToAllServers(LexoCorpServer);
var RhoConstructionServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "rho-construction", "Rho Construction", false, false, false, 0);
RhoConstructionServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(475, 525), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(500000000, 700000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40, 60), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40, 60));
RhoConstructionServer.setPortProperties(3);
AddToAllServers(RhoConstructionServer);
var AlphaEnterprisesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "alpha-ent", "Alpha Enterprises", false, false, false, 0);
AlphaEnterprisesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 600), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(600000000, 750000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 70), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 60));
AlphaEnterprisesServer.setPortProperties(4);
AlphaEnterprisesServer.messages.push("sector-12-crime.lit");
AddToAllServers(AlphaEnterprisesServer);
var AevumPoliceServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "aevum-police", "Aevum Police Network", false, false, false, 0);
AevumPoliceServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(400, 450), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(200000000, 400000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(30, 50));
AevumPoliceServer.setPortProperties(4);
AddToAllServers(AevumPoliceServer);
var RothmanUniversityServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "rothman-uni", "Rothman University Network", false, false, false, 4);
RothmanUniversityServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(370, 430), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(175000000, 250000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 55), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 45));
RothmanUniversityServer.setPortProperties(3);
RothmanUniversityServer.messages.push("secret-societies.lit");
RothmanUniversityServer.messages.push("the-failed-frontier.lit");
RothmanUniversityServer.messages.push("tensions-in-tech-race.lit");
AddToAllServers(RothmanUniversityServer);
var ZBInstituteOfTechnologyServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "zb-institute", "ZB Institute of Technology Network", false, false, false, 4);
ZBInstituteOfTechnologyServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(725, 775), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(800000000, 1100000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(65, 85), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(75, 85));
ZBInstituteOfTechnologyServer.setPortProperties(5);
AddToAllServers(ZBInstituteOfTechnologyServer);
var SummitUniversityServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "summit-uni", "Summit University Network", false, false, false, 4);
SummitUniversityServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(425, 475), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(200000000, 350000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40, 60));
SummitUniversityServer.setPortProperties(3);
SummitUniversityServer.messages.push("secret-societies.lit");
SummitUniversityServer.messages.push("the-failed-frontier.lit");
SummitUniversityServer.messages.push("synthetic-muscles.lit");
AddToAllServers(SummitUniversityServer);
var SysCoreSecuritiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "syscore", "SysCore Securities", false, false, false, 0);
SysCoreSecuritiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(550, 650), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(400000000, 600000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 70));
SysCoreSecuritiesServer.setPortProperties(4);
AddToAllServers(SysCoreSecuritiesServer);
var CatalystVenturesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "catalyst", "Catalyst Ventures", false, false, false, 0);
CatalystVenturesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(400, 450), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(300000000, 550000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 70), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(25, 55));
CatalystVenturesServer.setPortProperties(3);
CatalystVenturesServer.messages.push("tensions-in-tech-race.lit");
AddToAllServers(CatalystVenturesServer);
var TheHubServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "the-hub", "The Hub", false, false, false, 0);
TheHubServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(275, 325), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(150000000, 200000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 45), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 55));
TheHubServer.setPortProperties(2);
AddToAllServers(TheHubServer);
var CompuTekServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "comptek", "CompuTek", false, false, false, 8);
CompuTekServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(300, 400), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(220000000, 250000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 65));
CompuTekServer.setPortProperties(3);
CompuTekServer.messages.push("man-and-machine.lit");
AddToAllServers(CompuTekServer);
var NetLinkTechnologiesServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "netlink", "NetLink Technologies", false, false, false, 0);
NetLinkTechnologiesServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(375, 425), 275000000, Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60, 80), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 75));
NetLinkTechnologiesServer.setPortProperties(3);
NetLinkTechnologiesServer.messages.push("simulated-reality.lit");
AddToAllServers(NetLinkTechnologiesServer);
var JohnsonOrthopedicsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "johnson-ortho", "Johnson Orthopedics", false, false, false, 4);
JohnsonOrthopedicsServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(250, 300), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(70000000, 85000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 65));
JohnsonOrthopedicsServer.setPortProperties(2);
AddToAllServers(JohnsonOrthopedicsServer);
//"Low level" targets
var FoodNStuffServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "foodnstuff", "Food N Stuff Supermarket", false, false, false, 8);
FoodNStuffServer.setHackingParameters(1, 2000000, 10, 5);
FoodNStuffServer.setPortProperties(0);
FoodNStuffServer.messages.push("sector-12-crime.lit");
AddToAllServers(FoodNStuffServer);
var SigmaCosmeticsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "sigma-cosmetics", "Sigma Cosmetics", false, false, false, 8);
SigmaCosmeticsServer.setHackingParameters(5, 2300000, 10, 10);
SigmaCosmeticsServer.setPortProperties(0);
AddToAllServers(SigmaCosmeticsServer);
var JoesGunsServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "joesguns", "Joe's Guns", false, false, false, 8);
JoesGunsServer.setHackingParameters(10, 2500000, 15, 20);
JoesGunsServer.setPortProperties(0);
AddToAllServers(JoesGunsServer);
var Zer0NightclubServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "zer0", "ZER0 Nightclub", false, false, false, 4);
Zer0NightclubServer.setHackingParameters(75, 7500000, 25, 40);
Zer0NightclubServer.setPortProperties(1);
AddToAllServers(Zer0NightclubServer);
var NectarNightclubServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "nectar-net", "Nectar Nightclub Network", false, false, false, 8);
NectarNightclubServer.setHackingParameters(20, 2750000, 20, 25);
NectarNightclubServer.setPortProperties(0);
AddToAllServers(NectarNightclubServer);
var NeoNightclubServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "neo-net", "Neo Nightclub Network", false, false, false, 4);
NeoNightclubServer.setHackingParameters(50, 5000000, 25, 25);
NeoNightclubServer.setPortProperties(1);
NeoNightclubServer.messages.push("the-hidden-world.lit");
AddToAllServers(NeoNightclubServer);
var SilverHelixServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "silver-helix", "Silver Helix", false, false, false, 2);
SilverHelixServer.setHackingParameters(150, 45000000, 30, 30);
SilverHelixServer.setPortProperties(2);
SilverHelixServer.messages.push("new-triads.lit");
AddToAllServers(SilverHelixServer);
var HongFangTeaHouseServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "hong-fang-tea", "HongFang Teahouse", false, false, false, 8);
HongFangTeaHouseServer.setHackingParameters(30, 3000000, 15, 20);
HongFangTeaHouseServer.setPortProperties(0);
HongFangTeaHouseServer.messages.push("brighter-than-the-sun.lit");
AddToAllServers(HongFangTeaHouseServer);
var HaraKiriSushiBarServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "harakiri-sushi", "HaraKiri Sushi Bar Network", false, false, false, 8);
HaraKiriSushiBarServer.setHackingParameters(40, 4000000, 15, 40);
HaraKiriSushiBarServer.setPortProperties(0);
AddToAllServers(HaraKiriSushiBarServer);
var PhantasyServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "phantasy", "Phantasy Club", false, false, false, 0);
PhantasyServer.setHackingParameters(100, 24000000, 20, 35);
PhantasyServer.setPortProperties(2);
AddToAllServers(PhantasyServer);
var MaxHardwareServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "max-hardware", "Max Hardware Store", false, false, false, 4);
MaxHardwareServer.setHackingParameters(80, 10000000, 15, 30);
MaxHardwareServer.setPortProperties(1);
AddToAllServers(MaxHardwareServer);
var OmegaSoftwareServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "omega-net", "Omega Software", false, false, false, 8);
OmegaSoftwareServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(180, 220), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(60000000, 70000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(25, 35), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(30, 40));
OmegaSoftwareServer.setPortProperties(2);
OmegaSoftwareServer.messages.push("the-new-god.lit");
AddToAllServers(OmegaSoftwareServer);
//Gyms
var CrushFitnessGymServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "crush-fitness", "Crush Fitness", false, false, false, 0);
CrushFitnessGymServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(225, 275), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40000000, 60000000), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(35, 45), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(27, 33));
CrushFitnessGymServer.setPortProperties(2);
AddToAllServers(CrushFitnessGymServer);
var IronGymServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "iron-gym", "Iron Gym Network", false, false, false, 4);
IronGymServer.setHackingParameters(100, 20000000, 30, 20);
IronGymServer.setPortProperties(1);
AddToAllServers(IronGymServer);
var MilleniumFitnessGymServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "millenium-fitness", "Millenium Fitness Network", false, false, false, 0);
MilleniumFitnessGymServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(475, 525), 250000000, Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(45, 55), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(25, 45));
MilleniumFitnessGymServer.setPortProperties(3);
AddToAllServers(MilleniumFitnessGymServer);
var PowerhouseGymServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "powerhouse-fitness", "Powerhouse Fitness", false, false, false, 0);
PowerhouseGymServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(950, 1100), 900000000, Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(55, 65), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(50, 60));
PowerhouseGymServer.setPortProperties(5);
AddToAllServers(PowerhouseGymServer);
var SnapFitnessGymServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "snap-fitness", "Snap Fitness", false, false, false, 0);
SnapFitnessGymServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(675, 800), 450000000, Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40, 60), Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(40, 60));
SnapFitnessGymServer.setPortProperties(4);
AddToAllServers(SnapFitnessGymServer);
//Faction servers, cannot hack money from these
var BitRunnersServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "run4theh111z", "The Runners", false, false, false, 0);
BitRunnersServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(505, 550), 0, 0, 0);
BitRunnersServer.setPortProperties(4);
BitRunnersServer.messages.push("simulated-reality.lit");
BitRunnersServer.messages.push("the-new-god.lit");
AddToAllServers(BitRunnersServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].BitRunnersServer, BitRunnersServer.ip);
var TheBlackHandServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "I.I.I.I", "I.I.I.I", false, false, false, 0);
TheBlackHandServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(340, 365), 0, 0, 0);
TheBlackHandServer.setPortProperties(3);
TheBlackHandServer.messages.push("democracy-is-dead.lit");
AddToAllServers(TheBlackHandServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].TheBlackHandServer, TheBlackHandServer.ip);
var NiteSecServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "avmnite-02h", "NiteSec", false, false, false, 0);
NiteSecServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(202, 220), 0, 0, 0);
NiteSecServer.setPortProperties(2);
NiteSecServer.messages.push("democracy-is-dead.lit");
AddToAllServers(NiteSecServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].NiteSecServer, NiteSecServer.ip);
var DarkArmyServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), ".", ".", false, false, false, 0);
DarkArmyServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(505, 550), 0, 0, 0);
DarkArmyServer.setPortProperties(4);
AddToAllServers(DarkArmyServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].TheDarkArmyServer, DarkArmyServer.ip);
var CyberSecServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "CSEC", "CyberSec", false, false, false, 0);
CyberSecServer.setHackingParameters(Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["d" /* getRandomInt */])(51, 60), 0, 0, 0);
CyberSecServer.setPortProperties(1);
CyberSecServer.messages.push("democracy-is-dead.lit");
AddToAllServers(CyberSecServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].CyberSecServer, CyberSecServer.ip);
var DaedalusServer = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), "The-Cave", "Helios", false, false, false, 0);
DaedalusServer.setHackingParameters(925, 0, 0, 0);
DaedalusServer.setPortProperties(5);
DaedalusServer.messages.push("alpha-omega.lit");
AddToAllServers(DaedalusServer);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].DaedalusServer, DaedalusServer.ip);
//Super special Servers
var WorldDaemon = new Server(Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["a" /* createRandomIp */])(), __WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon, __WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon, false, false, false, 0);
WorldDaemon.setHackingParameters(3000, 0, 0, 0);
WorldDaemon.setPortProperties(5);
AddToAllServers(WorldDaemon);
__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp(__WEBPACK_IMPORTED_MODULE_5__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon, WorldDaemon.ip);
/* Create a randomized network for all the foreign servers */
//Groupings for creating a randomized network
var NetworkGroup1 = [IronGymServer, FoodNStuffServer, SigmaCosmeticsServer, JoesGunsServer, HongFangTeaHouseServer, HaraKiriSushiBarServer];
var NetworkGroup2 = [MaxHardwareServer, NectarNightclubServer, Zer0NightclubServer, CyberSecServer];
var NetworkGroup3 = [OmegaSoftwareServer, PhantasyServer, SilverHelixServer, NeoNightclubServer];
var NetworkGroup4 = [CrushFitnessGymServer, NetLinkTechnologiesServer, CompuTekServer, TheHubServer, JohnsonOrthopedicsServer, NiteSecServer];
var NetworkGroup5 = [CatalystVenturesServer, SysCoreSecuritiesServer, SummitUniversityServer, ZBInstituteOfTechnologyServer, RothmanUniversityServer, TheBlackHandServer];
var NetworkGroup6 = [LexoCorpServer, RhoConstructionServer, AlphaEnterprisesServer, AevumPoliceServer, MilleniumFitnessGymServer];
var NetworkGroup7 = [GlobalPharmaceuticalsServer, AeroCorpServer, GalacticCyberSystemsServer, SnapFitnessGymServer];
var NetworkGroup8 = [DeltaOneServer, UnitaLifeGroupServer, OmniaCybersystemsServer];
var NetworkGroup9 = [ZeusMedicalServer, SolarisSpaceSystemsServer, UniversalEnergyServer, IcarusMicrosystemsServer, DefCommServer];
var NetworkGroup10 = [NovaMedicalServer, ZBDefenseServer, TaiYangDigitalServer, InfoCommServer];
var NetworkGroup11 = [AppliedEnergeticsServer, MicrodyneTechnologiesServer, TitanLabsServer, BitRunnersServer];
var NetworkGroup12 = [VitaLifeServer, HeliosLabsServer, StormTechnologiesServer, FulcrumTechnologiesServer];
var NetworkGroup13 = [KuaiGongInternationalServer, FourSigmaServer, OmniTekIncorporatedServer, DarkArmyServer];
var NetworkGroup14 = [PowerhouseGymServer, ClarkeIncorporatedServer, NWOServer, BladeIndustriesServer, BachmanAndAssociatesServer];
var NetworkGroup15 = [FulcrumSecretTechnologiesServer, MegaCorpServer, ECorpServer, DaedalusServer];
for (var i = 0; i < NetworkGroup2.length; i++) {
var randomServerFromPrevGroup = NetworkGroup1[Math.floor(Math.random() * NetworkGroup1.length)];
NetworkGroup2[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup2[i].ip);
}
for (var i = 0; i < NetworkGroup3.length; i++) {
var randomServerFromPrevGroup = NetworkGroup2[Math.floor(Math.random() * NetworkGroup2.length)];
NetworkGroup3[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup3[i].ip);
}
for (var i = 0; i < NetworkGroup4.length; i++) {
var randomServerFromPrevGroup = NetworkGroup3[Math.floor(Math.random() * NetworkGroup3.length)];
NetworkGroup4[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup4[i].ip);
}
for (var i = 0; i < NetworkGroup5.length; i++) {
var randomServerFromPrevGroup = NetworkGroup4[Math.floor(Math.random() * NetworkGroup4.length)];
NetworkGroup5[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup5[i].ip);
}
for (var i = 0; i < NetworkGroup6.length; i++) {
var randomServerFromPrevGroup = NetworkGroup5[Math.floor(Math.random() * NetworkGroup5.length)];
NetworkGroup6[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup6[i].ip);
}
for (var i = 0; i < NetworkGroup7.length; i++) {
var randomServerFromPrevGroup = NetworkGroup6[Math.floor(Math.random() * NetworkGroup6.length)];
NetworkGroup7[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup7[i].ip);
}
for (var i = 0; i < NetworkGroup8.length; i++) {
var randomServerFromPrevGroup = NetworkGroup7[Math.floor(Math.random() * NetworkGroup7.length)];
NetworkGroup8[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup8[i].ip);
}
for (var i = 0; i < NetworkGroup9.length; i++) {
var randomServerFromPrevGroup = NetworkGroup8[Math.floor(Math.random() * NetworkGroup8.length)];
NetworkGroup9[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup9[i].ip);
}
for (var i = 0; i < NetworkGroup10.length; i++) {
var randomServerFromPrevGroup = NetworkGroup9[Math.floor(Math.random() * NetworkGroup9.length)];
NetworkGroup10[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup10[i].ip);
}
for (var i = 0; i < NetworkGroup11.length; i++) {
var randomServerFromPrevGroup = NetworkGroup10[Math.floor(Math.random() * NetworkGroup10.length)];
NetworkGroup11[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup11[i].ip);
}
for (var i = 0; i < NetworkGroup12.length; i++) {
var randomServerFromPrevGroup = NetworkGroup11[Math.floor(Math.random() * NetworkGroup11.length)];
NetworkGroup12[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup12[i].ip);
}
for (var i = 0; i < NetworkGroup13.length; i++) {
var randomServerFromPrevGroup = NetworkGroup12[Math.floor(Math.random() * NetworkGroup12.length)];
NetworkGroup13[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup13[i].ip);
}
for (var i = 0; i < NetworkGroup14.length; i++) {
var randomServerFromPrevGroup = NetworkGroup13[Math.floor(Math.random() * NetworkGroup13.length)];
NetworkGroup14[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup14[i].ip);
}
for (var i = 0; i < NetworkGroup15.length; i++) {
var randomServerFromPrevGroup = NetworkGroup14[Math.floor(Math.random() * NetworkGroup14.length)];
NetworkGroup15[i].serversOnNetwork.push(randomServerFromPrevGroup.ip);
randomServerFromPrevGroup.serversOnNetwork.push(NetworkGroup15[i].ip);
}
//Connect the first tier of servers to the player's home computer
for (var i = 0; i < NetworkGroup1.length; i++) {
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].getHomeComputer().serversOnNetwork.push(NetworkGroup1[i].ip);
NetworkGroup1[i].serversOnNetwork.push(__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].homeComputer);
}
}
//Applied server growth for a single server. Returns the percentage growth
function processSingleServerGrowth(server, numCycles) {
//Server growth processed once every 450 game cycles
var numServerGrowthCycles = Math.max(Math.floor(numCycles / 450), 0);
//Get adjusted growth rate, which accounts for server security
var growthRate = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ServerBaseGrowthRate;
var adjGrowthRate = 1 + (growthRate - 1) / server.hackDifficulty;
if (adjGrowthRate > __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ServerMaxGrowthRate) {adjGrowthRate = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ServerMaxGrowthRate;}
//Calculate adjusted server growth rate based on parameters
var serverGrowthPercentage = server.serverGrowth / 100;
var numServerGrowthCyclesAdjusted = numServerGrowthCycles * serverGrowthPercentage * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ServerGrowthRate;
//Apply serverGrowth for the calculated number of growth cycles
var serverGrowth = Math.pow(adjGrowthRate, numServerGrowthCyclesAdjusted * __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hacking_grow_mult);
if (serverGrowth < 1) {
console.log("WARN: serverGrowth calculated to be less than 1");
serverGrowth = 1;
}
server.moneyAvailable *= serverGrowth;
if (server.moneyMax && isNaN(server.moneyAvailable)) {
server.moneyAvailable = server.moneyMax;
}
if (server.moneyMax && server.moneyAvailable > server.moneyMax) {
server.moneyAvailable = server.moneyMax;
return 1;
}
//Growing increases server security twice as much as hacking
server.fortify(2 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ServerFortifyAmount * numServerGrowthCycles);
return serverGrowth;
}
function prestigeHomeComputer(homeComp) {
homeComp.programs.length = 0;
homeComp.runningScripts = [];
homeComp.serversOnNetwork = [];
homeComp.isConnectedTo = true;
homeComp.ramUsed = 0;
homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].NukeProgram);
homeComp.messages.length = 0;
}
//List of all servers that exist in the game, indexed by their ip
let AllServers = {};
function prestigeAllServers() {
for (var member in AllServers) {
delete AllServers[member];
}
AllServers = {};
}
function loadAllServers(saveString) {
AllServers = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */]);
}
function SizeOfAllServers() {
var size = 0, key;
for (key in AllServers) {
if (AllServers.hasOwnProperty(key)) size++;
}
return size;
}
//Add a server onto the map of all servers in the game
function AddToAllServers(server) {
var serverIp = server.ip;
if (Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["b" /* ipExists */])(serverIp)) {
console.log("IP of server that's being added: " + serverIp);
console.log("Hostname of the server thats being added: " + server.hostname);
console.log("The server that already has this IP is: " + AllServers[serverIp].hostname);
throw new Error("Error: Trying to add a server with an existing IP");
return;
}
AllServers[serverIp] = server;
}
//Returns server object with corresponding hostname
// Relatively slow, would rather not use this a lot
function GetServerByHostname(hostname) {
for (var ip in AllServers) {
if (AllServers.hasOwnProperty(ip)) {
if (AllServers[ip].hostname == hostname) {
return AllServers[ip];
}
}
}
return null;
}
//Get server by IP or hostname. Returns null if invalid
function getServer(s) {
if (!Object(__WEBPACK_IMPORTED_MODULE_7__utils_IPAddress_js__["c" /* isValidIPAddress */])(s)) {
return GetServerByHostname(s);
} else {
return AllServers[s];
}
}
//Debugging tool
function PrintAllServers() {
for (var ip in AllServers) {
if (AllServers.hasOwnProperty(ip)) {
console.log("Ip: " + ip + ", hostname: " + AllServers[ip].hostname);
}
}
}
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Reviver; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Generic_toJSON; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Generic_fromJSON; });
/* Generic Reviver, toJSON, and fromJSON functions used for saving and loading objects */
// A generic "smart reviver" function.
// Looks for object values with a `ctor` property and
// a `data` property. If it finds them, and finds a matching
// constructor that has a `fromJSON` property on it, it hands
// off to that `fromJSON` fuunction, passing in the value.
function Reviver(key, value) {
var ctor;
if (value == null) {
console.log("Reviver WRONGLY called with key: " + key + ", and value: " + value);
return 0;
}
if (typeof value === "object" &&
typeof value.ctor === "string" &&
typeof value.data !== "undefined") {
ctor = Reviver.constructors[value.ctor] || window[value.ctor];
if (typeof ctor === "function" &&
typeof ctor.fromJSON === "function") {
return ctor.fromJSON(value);
}
}
return value;
}
Reviver.constructors = {}; // A list of constructors the smart reviver should know about
// A generic "toJSON" function that creates the data expected
// by Reviver.
// `ctorName` The name of the constructor to use to revive it
// `obj` The object being serialized
// `keys` (Optional) Array of the properties to serialize,
// if not given then all of the objects "own" properties
// that don't have function values will be serialized.
// (Note: If you list a property in `keys`, it will be serialized
// regardless of whether it's an "own" property.)
// Returns: The structure (which will then be turned into a string
// as part of the JSON.stringify algorithm)
function Generic_toJSON(ctorName, obj, keys) {
var data, index, key;
if (!keys) {
keys = Object.keys(obj); // Only "own" properties are included
}
data = {};
for (index = 0; index < keys.length; ++index) {
key = keys[index];
data[key] = obj[key];
}
return {ctor: ctorName, data: data};
}
// A generic "fromJSON" function for use with Reviver: Just calls the
// constructor function with no arguments, then applies all of the
// key/value pairs from the raw data to the instance. Only useful for
// constructors that can be reasonably called without arguments!
// `ctor` The constructor to call
// `data` The data to apply
// Returns: The object
function Generic_fromJSON(ctor, data) {
var obj, name;
obj = new ctor();
for (name in data) {
obj[name] = data[name];
}
return obj;
}
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* jQuery JavaScript Library v3.2.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2017-03-20T18:59Z
*/
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var
version = "3.2.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
// Return all the elements in a clean array
if ( num == null ) {
return slice.call( this );
}
// Return just the one element from the set
return num < 0 ? this[ num + this.length ] : this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
DOMEval( code );
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.3
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-08-08
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true && ("form" in elem || "label" in elem);
},
{ dir: "parentNode", next: "legend" }
);
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
disabledAncestor( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID filter and find
if ( support.getById ) {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var elem = context.getElementById( id );
return elem ? [ elem ] : [];
}
};
} else {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var node, i, elems,
elem = context.getElementById( id );
if ( elem ) {
// Verify the id attribute
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
// Fall back on getElementsByName
elems = context.getElementsByName( id );
i = 0;
while ( (elem = elems[i++]) ) {
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
}
}
return [];
}
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( true ),
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
return false;
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
return false;
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( el ) {
return el.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
function nodeName( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
};
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Simple selector that can be filtered directly, removing non-Elements
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
// Complex selector, compare the two sets, removing non-Elements
qualifier = jQuery.filter( qualifier, elements );
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
if ( elems.length === 1 && elem.nodeType === 1 ) {
return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
}
return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
if ( nodeName( elem, "iframe" ) ) {
return elem.contentDocument;
}
// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
// Treat the template element as a regular one in browsers that
// don't support it.
if ( nodeName( elem, "template" ) ) {
elem = elem.content || elem;
}
return jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = locked || options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject, noValue ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
// * false: [ value ].slice( 0 ) => resolve( value )
// * true: [ value ].slice( 1 ) => resolve()
resolve.apply( undefined, [ value ].slice( noValue ) );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.apply( undefined, [ value ] );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( jQuery.isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
!remaining );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList
.then( fn )
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch( function( error ) {
jQuery.readyException( error );
} );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
if ( chainable ) {
return elems;
}
// Gets
if ( bulk ) {
return fn.call( elems );
}
return len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
( ( key && typeof key === "string" ) && value === undefined ) ) {
return this.get( owner, key );
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( Array.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnothtmlwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function getData( data ) {
if ( data === "true" ) {
return true;
}
if ( data === "false" ) {
return false;
}
if ( data === "null" ) {
return null;
}
// Only convert to a number if it doesn't change the string
if ( data === +data + "" ) {
return +data;
}
if ( rbrace.test( data ) ) {
return JSON.parse( data );
}
return data;
}
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = getData( data );
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || Array.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) );
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
if ( typeof context.getElementsByTagName !== "undefined" ) {
ret = context.getElementsByTagName( tag || "*" );
} else if ( typeof context.querySelectorAll !== "undefined" ) {
ret = context.querySelectorAll( tag || "*" );
} else {
ret = [];
}
if ( tag === undefined || tag && nodeName( context, tag ) ) {
return jQuery.merge( [ context ], ret );
}
return ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, selector );
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, handleObj, sel, matchedHandlers, matchedSelectors,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
if ( delegateCount &&
// Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType &&
// Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!( event.type === "click" && event.button >= 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
matchedHandlers = [];
matchedSelectors = {};
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matchedSelectors[ sel ] === undefined ) {
matchedSelectors[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matchedSelectors[ sel ] ) {
matchedHandlers.push( handleObj );
}
}
if ( matchedHandlers.length ) {
handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
}
}
}
}
// Add the remaining (directly-bound) handlers
cur = this;
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
if ( button & 1 ) {
return 1;
}
if ( button & 2 ) {
return 3;
}
if ( button & 4 ) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
if ( nodeName( elem, "table" ) &&
nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return jQuery( ">tbody", elem )[ 0 ] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
div.style.cssText =
"box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
container.appendChild( div );
jQuery.extend( support, {
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
// Support: Firefox 51+
// Retrieving style before computed somehow
// fixes an issue with getting wrong values
// on detached elements
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is needed for:
// .css('filter') (IE 9 only, #12537)
// .css('--customProperty) (#3144)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rcustomProp = /^--/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
// Return a property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName( name ) {
var ret = jQuery.cssProps[ name ];
if ( !ret ) {
ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;
}
return ret;
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i,
val = 0;
// If we already have the right measurement, avoid augmentation
if ( extra === ( isBorderBox ? "border" : "content" ) ) {
i = 4;
// Otherwise initialize for horizontal or vertical properties
} else {
i = name === "width" ? 1 : 0;
}
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// At this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// At this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with computed style
var valueIsBorderBox,
styles = getStyles( elem ),
val = curCSS( elem, name, styles ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Fall back to offsetWidth/Height when value is "auto"
// This happens for inline elements with no explicit setting (gh-3571)
if ( val === "auto" ) {
val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ];
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
isCustomProp = rcustomProp.test( name ),
style = elem.style;
// Make sure that we're working with the right name. We don't
// want to query the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
if ( isCustomProp ) {
style.setProperty( name, value );
} else {
style[ name ] = value;
}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name ),
isCustomProp = rcustomProp.test( name );
// Make sure that we're working with the right name. We don't
// want to modify the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( Array.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
}
} );
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || jQuery.easing._default;
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, inProgress,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function schedule() {
if ( inProgress ) {
if ( document.hidden === false && window.requestAnimationFrame ) {
window.requestAnimationFrame( schedule );
} else {
window.setTimeout( schedule, jQuery.fx.interval );
}
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// Ensure the complete handler is called before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* eslint-disable no-loop-func */
anim.done( function() {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( Array.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3 only
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ] );
// If there's more to do, yield
if ( percent < 1 && length ) {
return remaining;
}
// If this was an empty animation, synthesize a final progress notification
if ( !length ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
}
// Resolve the animation and report its conclusion
deferred.resolveWith( elem, [ animation ] );
return false;
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
} ),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length; index++ ) {
result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
// Attach callbacks from options
animation
.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
return animation;
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnothtmlwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
// Go to the end state if fx are off
if ( jQuery.fx.off ) {
opt.duration = 0;
} else {
if ( typeof opt.duration !== "number" ) {
if ( opt.duration in jQuery.fx.speeds ) {
opt.duration = jQuery.fx.speeds[ opt.duration ];
} else {
opt.duration = jQuery.fx.speeds._default;
}
}
}
// Normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// Show any hidden elements after setting opacity to 0
return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
// Animate to the value specified
.end().animate( { opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Run the timer and safely remove it when done (allowing for external removal)
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
jQuery.fx.start();
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( inProgress ) {
return;
}
inProgress = true;
schedule();
};
jQuery.fx.stop = function() {
inProgress = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
} )();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match( rnothtmlwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
if ( tabindex ) {
return parseInt( tabindex, 10 );
}
if (
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) &&
elem.href
) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// Strip and collapse whitespace according to HTML spec
// https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace
function stripAndCollapse( value ) {
var tokens = value.match( rnothtmlwhite ) || [];
return tokens.join( " " );
}
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnothtmlwhite ) || [];
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
return true;
}
}
return false;
}
} );
var rreturn = /\r/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( Array.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option, i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if ( index < 0 ) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( Array.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( Array.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// If an array was passed in, assume that it is an array of form elements.
if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( i, elem ) {
var val = jQuery( this ).val();
if ( val == null ) {
return null;
}
if ( Array.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rantiCache = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType[ 0 ] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR );
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( completed ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available, append data to url
if ( s.data ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add or update anti-cache param if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rantiCache, "$1" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend &&
( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( jQuery.isFunction( html ) ) {
html = html.call( this[ 0 ] );
}
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// Force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = stripAndCollapse( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var doc, docElem, rect, win,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
doc = elem.ownerDocument;
docElem = doc.documentElement;
win = doc.defaultView;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset = {
top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
};
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
// Coalesce documents and windows
var win;
if ( jQuery.isWindow( elem ) ) {
win = elem;
} else if ( elem.nodeType === 9 ) {
win = elem.defaultView;
}
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable );
};
} );
} );
jQuery.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
jQuery.holdReady = function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( true ) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return jQuery;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} );
/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initBitNodes; });
/* unused harmony export BitNode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return BitNodes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BitNodeMultipliers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initBitNodeMultipliers; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Player_js__ = __webpack_require__(0);
function BitNode(n, name, desc="", info="") {
this.number = n;
this.name = name;
this.desc = desc;
this.info = info;
}
let BitNodes = {};
function initBitNodes() {
BitNodes = {};
BitNodes["BitNode1"] = new BitNode(1, "Source Genesis", "The original BitNode",
"The first BitNode created by the Enders to imprison the minds of humans. It became " +
"the prototype and testing-grounds for all of the BitNodes that followed.<br><br>" +
"This is the first BitNode that you play through. It has no special " +
"modifications or mechanics.<br><br>" +
"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:<br><br>" +
"Level 1: 16%<br>" +
"Level 2: 24%<br>" +
"Level 3: 28%");
BitNodes["BitNode2"] = new BitNode(2, "Rise of the Underworld", "From the shadows, they rose", //Gangs
"From the shadows, they rose.<br><br>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.<br><br>" +
"In this BitNode:<br><br>The maximum amount of money available on a server is significantly decreased<br>" +
"The amount of money gained from crimes is doubled<br>" +
"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<br>" +
"Every Augmentation in the game will be available through the Factions listed above<br>" +
"For every Faction NOT listed above, reputation gains are halved<br>" +
"You will no longer gain passive reputation with Factions<br><br>" +
"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:<br><br>" +
"Level 1: 20%<br>" +
"Level 2: 30%<br>" +
"Level 3: 35%");
BitNodes["BitNode3"] = new BitNode(3, "The Price of Civilization", "COMING SOON"); //Corporate Warfare, Run own company
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. <br><br>" +
"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.<br><br>" +
"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.<br><br>" +
"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", "COMING SOON"); //Int
BitNodes["BitNode6"] = new BitNode(6, "Hacktocracy", "COMING SOON"); //Healthy Hacknet balancing mechanic
BitNodes["BitNode7"] = new BitNode(7, "Do Androids Dream?", "COMING SOON"); //Build androids for automation
BitNodes["BitNode8"] = new BitNode(8, "Ghost of Wall Street", "COMING SOON"); //Trading only viable strategy
BitNodes["BitNode9"] = new BitNode(9, "MegaCorp", "COMING SOON"); //Single corp/server with increasing difficulty
BitNodes["BitNode10"] = new BitNode(10, "Wasteland", "COMING SOON"); //Postapocalyptic
BitNodes["BitNode11"] = new BitNode(11, "The Big Crash", "Okay. Sell it all.", //Crashing economy
"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.<br><br>" +
"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.<br><br>" +
"In this BitNode:<br><br>" +
"The starting and maximum amount of money available on servers is significantly decreased<br>" +
"The growth rate of servers is halved<br>" +
"Weakening a server is twice as effective<br>" +
"Company wages are decreased by 50%<br>" +
"Hacknet Node production is significantly decreased<br>" +
"Augmentations are twice as expensive<br><br>" +
"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 increases the player's company salary and reputation gain multipliers by:<br><br>" +
"Level 1: 60%<br>" +
"Level 2: 90%<br>" +
"Level 3: 105%");
BitNodes["BitNode12"] = new BitNode(12, "Eye of the World", "COMING SOON"); //Become AI
}
let BitNodeMultipliers = {
ServerMaxMoney: 1,
ServerStartingMoney: 1,
ServerGrowthRate: 1,
ServerWeakenRate: 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,
AugmentationRepCost: 1,
AugmentationMoneyCost: 1,
}
function initBitNodeMultipliers() {
if (__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].bitNodeN == null) {
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].bitNodeN = 1;
}
for (var mult in BitNodeMultipliers) {
if (BitNodeMultipliers.hasOwnProperty(mult)) {
BitNodeMultipliers[mult] = 1;
}
}
switch (__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].bitNodeN) {
case 1:
break;
case 2: //Rise of the Underworld
BitNodeMultipliers.ServerMaxMoney = 0.2;
BitNodeMultipliers.CrimeMoney = 2;
BitNodeMultipliers.FactionWorkRepGain = 0.5;
BitNodeMultipliers.FactionPassiveRepGain = 0;
break;
case 4: //The Singularity
BitNodeMultipliers.ServerMaxMoney = 0.15;
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 11: //The Big Crash
BitNodeMultipliers.ServerMaxMoney = 0.1;
BitNodeMultipliers.ServerStartingMoney = 0.25;
BitNodeMultipliers.ServerGrowthRate = 0.5;
BitNodeMultipliers.ServerWeakenRate = 2;
BitNodeMultipliers.CompanyWorkMoney = 0.5;
BitNodeMultipliers.HacknetNodeMoney = 0.1;
BitNodeMultipliers.AugmentationMoneyCost = 2;
break;
default:
console.log("WARNING: Player.bitNodeN invalid");
break;
}
}
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getNextNeurofluxLevel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Factions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return initFactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return inviteToFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return joinFaction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayFactionContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return processPassiveFactionRepGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return loadFactions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Faction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return purchaseAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return factionExists; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__ = __webpack_require__(53);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_FactionInvitationBox_js__ = __webpack_require__(54);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__ = __webpack_require__(20);
//Netburner Faction class
function factionInit() {
$('#faction-donate-input').on('input', function() {
if (__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].Page.Faction) {
var val = document.getElementById("faction-donate-input").value;
if (Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["d" /* isPositiveNumber */])(val)) {
var numMoneyDonate = Number(val);
document.getElementById("faction-donate-rep-gain").innerHTML =
"This donation will result in " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(numMoneyDonate/1000000 * __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].faction_rep_mult, 3) + " reputation gain";
} else {
document.getElementById("faction-donate-rep-gain").innerHTML =
"This donation will result in 0 reputation gain";
}
}
});
}
document.addEventListener("DOMContentLoaded", factionInit, false);
function Faction(name="") {
this.name = name;
this.augmentations = []; //Name of augmentation only
this.info = ""; //Introductory/informational text about the faction
//Player-related properties for faction
this.isMember = false; //Whether player is member
this.isBanned = false; //Whether or not player is banned from joining this faction
this.playerReputation = 0; //"Reputation" within faction
this.alreadyInvited = false;
//Multipliers for unlocking and purchasing augmentations
this.augmentationPriceMult = 1;
this.augmentationRepRequirementMult = 1;
//Faction favor
this.favor = 0;
this.rolloverRep = 0;
};
Faction.prototype.setAugmentationMultipliers = function(price, rep) {
this.augmentationPriceMult = price;
this.augmentationRepRequirementMult = rep;
}
Faction.prototype.setInfo = function(inf) {
this.info = inf;
}
Faction.prototype.gainFavor = function() {
if (this.favor == null || this.favor == undefined) {this.favor = 0;}
if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;}
var res = this.getFavorGain();
if (res.length != 2) {
console.log("Error: invalid result from getFavorGain() function");
return;
}
this.favor += res[0];
this.rolloverRep = res[1];
}
//Returns an array with [How much favor would be gained, how much favor would be left over]
Faction.prototype.getFavorGain = function() {
if (this.favor == null || this.favor == undefined) {this.favor = 0;}
if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;}
var favorGain = 0, rep = this.playerReputation + this.rolloverRep;
var reqdRep = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].FactionReputationToFavorBase *
Math.pow(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].FactionReputationToFavorMult, this.favor);
while(rep > 0) {
if (rep >= reqdRep) {
++favorGain;
rep -= reqdRep;
} else {
break;
}
reqdRep *= __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].FactionReputationToFavorMult;
}
return [favorGain, rep];
}
//Adds all Augmentations to this faction.
Faction.prototype.addAllAugmentations = function() {
this.augmentations.length = 0;
for (var name in __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */]) {
if (__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */].hasOwnProperty(name)) {
this.augmentations.push(name);
}
}
}
Faction.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_11__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Faction", this);
}
Faction.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_11__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Faction, value.data);
}
__WEBPACK_IMPORTED_MODULE_11__utils_JSONReviver_js__["c" /* Reviver */].constructors.Faction = Faction;
//Map of factions indexed by faction name
let Factions = {}
function loadFactions(saveString) {
Factions = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_11__utils_JSONReviver_js__["c" /* Reviver */]);
}
function AddToFactions(faction) {
var name = faction.name;
Factions[name] = faction;
}
function factionExists(name) {
return Factions.hasOwnProperty(name);
}
//TODO Augmentation price and rep requirement mult are 1 for everything right now,
// This might change in the future for balance
function initFactions() {
//Endgame
var Illuminati = new Faction("Illuminati");
Illuminati.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].IlluminatiInfo);
if (factionExists("Illuminati")) {
Illuminati.favor = Factions["Illuminati"].favor;
delete Factions["Illuminati"];
}
AddToFactions(Illuminati);
var Daedalus = new Faction("Daedalus");
Daedalus.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].DaedalusInfo);
if (factionExists("Daedalus")) {
Daedalus.favor = Factions["Daedalus"].favor;
delete Factions["Daedalus"];
}
AddToFactions(Daedalus);
var Covenant = new Faction("The Covenant");
Covenant.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].CovenantInfo);
if (factionExists("The Covenant")) {
Covenant.favor = Factions["The Covenant"].favor;
delete Factions["The Covenant"];
}
AddToFactions(Covenant);
//Megacorporations, each forms its own faction
var ECorp = new Faction("ECorp");
ECorp.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].ECorpInfo);
if (factionExists("ECorp")) {
ECorp.favor = Factions["ECorp"].favor;
delete Factions["ECorp"];
}
AddToFactions(ECorp);
var MegaCorp = new Faction("MegaCorp");
MegaCorp.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].MegaCorpInfo);
if (factionExists("MegaCorp")) {
MegaCorp.favor = Factions["MegaCorp"].favor;
delete Factions["MegaCorp"];
}
AddToFactions(MegaCorp);
var BachmanAndAssociates = new Faction("Bachman & Associates");
BachmanAndAssociates.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].BachmanAndAssociatesInfo);
if (factionExists("Bachman & Associates")) {
BachmanAndAssociates.favor = Factions["Bachman & Associates"].favor;
delete Factions["Bachman & Associates"];
}
AddToFactions(BachmanAndAssociates);
var BladeIndustries = new Faction("Blade Industries");
BladeIndustries.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].BladeIndustriesInfo);
if (factionExists("Blade Industries")) {
BladeIndustries.favor = Factions["Blade Industries"].favor;
delete Factions["Blade Industries"];
}
AddToFactions(BladeIndustries);
var NWO = new Faction("NWO");
NWO.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].NWOInfo);
if (factionExists("NWO")) {
NWO.favor = Factions["NWO"].favor;
delete Factions["NWO"];
}
AddToFactions(NWO);
var ClarkeIncorporated = new Faction("Clarke Incorporated");
ClarkeIncorporated.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].ClarkeIncorporatedInfo);
if (factionExists("Clarke Incorporated")) {
ClarkeIncorporated.favor = Factions["Clarke Incorporated"].favor;
delete Factions["Clarke Incorporated"];
}
AddToFactions(ClarkeIncorporated);
var OmniTekIncorporated = new Faction("OmniTek Incorporated");
OmniTekIncorporated.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].OmniTekIncorporatedInfo);
if (factionExists("OmniTek Incorporated")) {
OmniTekIncorporated.favor = Factions["OmniTek Incorporated"].favor;
delete Factions["OmniTek Incorporated"];
}
AddToFactions(OmniTekIncorporated);
var FourSigma = new Faction("Four Sigma");
FourSigma.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].FourSigmaInfo);
if (factionExists("Four Sigma")) {
FourSigma.favor = Factions["Four Sigma"].favor;
delete Factions["Four Sigma"];
}
AddToFactions(FourSigma);
var KuaiGongInternational = new Faction("KuaiGong International");
KuaiGongInternational.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].KuaiGongInternationalInfo);
if (factionExists("KuaiGong International")) {
KuaiGongInternational.favor = Factions["KuaiGong International"].favor;
delete Factions["KuaiGong International"];
}
AddToFactions(KuaiGongInternational);
//Other corporations
var FulcrumTechnologies = new Faction("Fulcrum Secret Technologies");
FulcrumTechnologies.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].FulcrumSecretTechnologiesInfo);
if (factionExists("Fulcrum Secret Technologies")) {
FulcrumTechnologies.favor = Factions["Fulcrum Secret Technologies"].favor;
delete Factions["Fulcrum Secret Technologies"];
}
AddToFactions(FulcrumTechnologies);
//Hacker groups
var BitRunners = new Faction("BitRunners");
BitRunners.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].BitRunnersInfo);
if (factionExists("BitRunners")) {
BitRunners.favor = Factions["BitRunners"].favor;
delete Factions["BitRunners"];
}
AddToFactions(BitRunners);
var BlackHand = new Faction("The Black Hand");
BlackHand.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].BlackHandInfo);
if (factionExists("The Black Hand")) {
BlackHand.favor = Factions["The Black Hand"].favor;
delete Factions["The Black Hand"];
}
AddToFactions(BlackHand);
var NiteSec = new Faction("NiteSec");
NiteSec.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].NiteSecInfo);
if (factionExists("NiteSec")) {
NiteSec.favor = Factions["NiteSec"].favor;
delete Factions["NiteSec"];
}
AddToFactions(NiteSec);
//City factions, essentially governments
var Chongqing = new Faction("Chongqing");
Chongqing.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].ChongqingInfo);
if (factionExists("Chongqing")) {
Chongqing.favor = Factions["Chongqing"].favor;
delete Factions["Chongqing"];
}
AddToFactions(Chongqing);
var Sector12 = new Faction("Sector-12");
Sector12.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].Sector12Info);
if (factionExists("Sector-12")) {
Sector12.favor = Factions["Sector-12"].favor;
delete Factions["Sector-12"];
}
AddToFactions(Sector12);
var NewTokyo = new Faction("New Tokyo");
NewTokyo.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].NewTokyoInfo);
if (factionExists("New Tokyo")) {
NewTokyo.favor = Factions["New Tokyo"].favor;
delete Factions["New Tokyo"];
}
AddToFactions(NewTokyo);
var Aevum = new Faction("Aevum");
Aevum.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].AevumInfo);
if (factionExists("Aevum")) {
Aevum.favor = Factions["Aevum"].favor;
delete Factions["Aevum"];
}
AddToFactions(Aevum);
var Ishima = new Faction("Ishima");
Ishima.setInfo
var Volhaven = new Faction("Volhaven");
Volhaven.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].VolhavenInfo);
if (factionExists("Volhaven")) {
Volhaven.favor = Factions["Volhaven"].favor;
delete Factions["Volhaven"];
}
AddToFactions(Volhaven);(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].IshimaInfo);
if (factionExists("Ishima")) {
Ishima.favor = Factions["Ishima"].favor;
delete Factions["Ishima"];
}
AddToFactions(Ishima);
//Criminal Organizations/Gangs
var SpeakersForTheDead = new Faction("Speakers for the Dead");
SpeakersForTheDead.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].SpeakersForTheDeadInfo);
if (factionExists("Speakers for the Dead")) {
SpeakersForTheDead.favor = Factions["Speakers for the Dead"].favor;
delete Factions["Speakers for the Dead"];
}
AddToFactions(SpeakersForTheDead);
var DarkArmy = new Faction("The Dark Army");
DarkArmy.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].DarkArmyInfo);
if (factionExists("The Dark Army")) {
DarkArmy.favor = Factions["The Dark Army"].favor;
delete Factions["The Dark Army"];
}
AddToFactions(DarkArmy);
var TheSyndicate = new Faction("The Syndicate");
TheSyndicate.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].TheSyndicateInfo);
if (factionExists("The Syndicate")) {
TheSyndicate.favor = Factions["The Syndicate"].favor;
delete Factions["The Syndicate"];
}
AddToFactions(TheSyndicate);
var Silhouette = new Faction("Silhouette");
Silhouette.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].SilhouetteInfo);
if (factionExists("Silhouette")) {
Silhouette.favor = Factions["Silhouette"].favor;
delete Factions["Silhouette"];
}
AddToFactions(Silhouette);
var Tetrads = new Faction("Tetrads"); //Low-medium level asian crime gang
Tetrads.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].TetradsInfo);
if (factionExists("Tetrads")) {
Tetrads.favor = Factions["Tetrads"].favor;
delete Factions["Tetrads"];
}
AddToFactions(Tetrads);
var SlumSnakes = new Faction("Slum Snakes"); //Low level crime gang
SlumSnakes.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].SlumSnakesInfo);
if (factionExists("Slum Snakes")) {
SlumSnakes.favor = Factions["Slum Snakes"].favor;
delete Factions["Slum Snakes"];
}
AddToFactions(SlumSnakes);
//Earlygame factions - factions the player will prestige with early on that don't
//belong in other categories
var Netburners = new Faction("Netburners");
Netburners.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].NetburnersInfo);
if (factionExists("Netburners")) {
Netburners.favor = Factions["Netburners"].favor;
delete Factions["Netburners"];
}
AddToFactions(Netburners);
var TianDiHui = new Faction("Tian Di Hui"); //Society of the Heaven and Earth
TianDiHui.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].TianDiHuiInfo);
if (factionExists("Tian Di Hui")) {
TianDiHui.favor = Factions["Tian Di Hui"].favor;
delete Factions["Tian Di Hui"];
}
AddToFactions(TianDiHui);
var CyberSec = new Faction("CyberSec");
CyberSec.setInfo(__WEBPACK_IMPORTED_MODULE_4__FactionInfo_js__["a" /* FactionInfo */].CyberSecInfo);
if (factionExists("CyberSec")) {
CyberSec.favor = Factions["CyberSec"].favor;
delete Factions["CyberSec"];
}
AddToFactions(CyberSec);
}
function inviteToFaction(faction) {
if (__WEBPACK_IMPORTED_MODULE_7__Settings_js__["a" /* Settings */].SuppressFactionInvites) {
faction.alreadyInvited = true;
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].factionInvitations.push(faction.name);
} else {
Object(__WEBPACK_IMPORTED_MODULE_9__utils_FactionInvitationBox_js__["a" /* factionInvitationBoxCreate */])(faction);
}
}
function joinFaction(faction) {
faction.isMember = true;
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].factions.push(faction.name);
//Determine what factions you are banned from now that you have joined this faction
if (faction.name == "Chongqing") {
Factions["Sector-12"].isBanned = true;
Factions["Aevum"].isBanned = true;
Factions["Volhaven"].isBanned = true;
} else if (faction.name == "Sector-12") {
Factions["Chongqing"].isBanned = true;
Factions["New Tokyo"].isBanned = true;
Factions["Ishima"].isBanned = true;
Factions["Volhaven"].isBanned = true;
} else if (faction.name == "New Tokyo") {
Factions["Sector-12"].isBanned = true;
Factions["Aevum"].isBanned = true;
Factions["Volhaven"].isBanned = true;
} else if (faction.name == "Aevum") {
Factions["Chongqing"].isBanned = true;
Factions["New Tokyo"].isBanned = true;
Factions["Ishima"].isBanned = true;
Factions["Volhaven"].isBanned = true;
} else if (faction.name == "Ishima") {
Factions["Sector-12"].isBanned = true;
Factions["Aevum"].isBanned = true;
Factions["Volhaven"].isBanned = true;
} else if (faction.name == "Volhaven") {
Factions["Chongqing"].isBanned = true;
Factions["Sector-12"].isBanned = true;
Factions["New Tokyo"].isBanned = true;
Factions["Aevum"].isBanned = true;
Factions["Ishima"].isBanned = true;
}
}
//Displays the HTML content for a specific faction
function displayFactionContent(factionName) {
var faction = Factions[factionName];
document.getElementById("faction-name").innerHTML = factionName;
document.getElementById("faction-info").innerHTML = "<i>" + faction.info + "</i>";
var repGain = faction.getFavorGain();
if (repGain.length != 2) {repGain = 0;}
repGain = repGain[0];
document.getElementById("faction-reputation").innerHTML = "Reputation: " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(faction.playerReputation, 4) +
"<span class='tooltiptext'>You will earn " +
Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(repGain, 4) +
" faction favor upon resetting after installing an Augmentation</span>";
document.getElementById("faction-favor").innerHTML = "Faction Favor: " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(faction.favor, 4) +
"<span class='tooltiptext'>Faction favor increases the rate at which " +
"you earn reputation for this faction by 1% per favor. Faction favor " +
"is gained whenever you reset after installing an Augmentation. The amount of " +
"favor you gain depends on how much reputation you have with the faction</span>";
var hackDiv = document.getElementById("faction-hack-div");
var fieldWorkDiv = document.getElementById("faction-fieldwork-div");
var securityWorkDiv = document.getElementById("faction-securitywork-div");
var donateDiv = document.getElementById("faction-donate-div");
var gangDiv = document.getElementById("faction-gang-div");
var newHackButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-hack-button");
var newFieldWorkButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-fieldwork-button");
var newSecurityWorkButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-securitywork-button");
var newDonateWorkButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-donate-button");
newHackButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].startFactionHackWork(faction);
return false;
});
newFieldWorkButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].startFactionFieldWork(faction);
return false;
});
newSecurityWorkButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].startFactionSecurityWork(faction);
return false;
});
newDonateWorkButton.addEventListener("click", function() {
var donateAmountVal = document.getElementById("faction-donate-input").value;
if (Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["d" /* isPositiveNumber */])(donateAmountVal)) {
var numMoneyDonate = Number(donateAmountVal);
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].money.lt(numMoneyDonate)) {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You cannot afford to donate this much money!");
return;
}
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].loseMoney(numMoneyDonate);
var repGain = numMoneyDonate / 1000000 * __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].faction_rep_mult;
faction.playerReputation += repGain;
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You just donated $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(numMoneyDonate, 2) + " to " +
faction.name + " to gain " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(repGain, 3) + " reputation");
displayFactionContent(factionName);
} else {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Invalid amount entered!");
}
return false;
});
var newPurchaseAugmentationsButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-purchase-augmentations");
newPurchaseAugmentationsButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].hideAllContent();
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].Display.factionAugmentationsContent.style.visibility = "visible";
var newBackButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-augmentations-back-button");
newBackButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadFactionContent();
displayFactionContent(factionName);
return false;
});
displayFactionAugmentations(factionName);
return false;
});
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].bitNodeN == 2 && (factionName == "Slum Snakes" || factionName == "Tetrads" ||
factionName == "The Syndicate" || factionName == "The Dark Army" || factionName == "Speakers for the Dead" ||
factionName == "NiteSec" || factionName == "The Black Hand")) {
//Set everything else to invisible
hackDiv.style.display = "none";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
donateDiv.style.display = "none";
var gangDiv = document.getElementById("faction-gang-div");
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].inGang() && __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].gang.facName != factionName) {
//If the player has a gang but its not for this faction
if (gangDiv) {
gangDiv.style.display = "none";
}
return;
}
//Create the "manage gang" button if it doesn't exist
if (gangDiv == null) {
gangDiv = document.createElement("div");
gangDiv.setAttribute("id", "faction-gang-div");
gangDiv.setAttribute("class", "faction-work-div");
gangDiv.style.display = "inline";
gangDiv.innerHTML =
'<div id="faction-gang-div-wrapper" class="faction-work-div-wrapper">' +
'<a id="faction-gang-button" class="a-link-button">Manage Gang</a>' +
'<p id="faction-gang-text">' +
'Create and manage a gang for this Faction. ' +
'Gangs will earn you money and faction reputation.' +
'</p>' +
'</div>' +
'<div class="faction-clear"></div>';
var descText = document.getElementById("faction-work-description-text");
if (descText) {
descText.parentNode.insertBefore(gangDiv, descText.nextSibling);
} else {
console.log("ERROR: faciton-work-description-text not found");
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Error loading this page. This is a bug please report to game developer");
return;
}
}
gangDiv.style.display = "inline";
var gangButton = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("faction-gang-button");
gangButton.addEventListener("click", function() {
if (!__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].inGang()) {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
yesBtn.innerHTML = "Create Gang";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", () => {
var hacking = false;
if (factionName === "NiteSec" || factionName === "The Black Hand") {hacking = true;}
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].startGang(factionName, hacking);
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadGangContent();
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
noBtn.addEventListener("click", () => {
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("Would you like to create a new Gang with " + factionName + "?<br><br>" +
"Note that this will prevent you from creating a Gang with any other Faction until " +
"this BitNode is destroyed. There are NO differences between the Factions you can " +
"create a Gang with and each of these Factions have all Augmentations available");
} else {
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadGangContent();
}
});
return;
} else {
if (gangDiv) {gangDiv.style.display = "none";}
}
if (faction.isMember) {
if (faction.favor >= 150) {
donateDiv.style.display = "inline";
} else {
donateDiv.style.display = "none";
}
switch(faction.name) {
case "Illuminati":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "Daedalus":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "The Covenant":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "ECorp":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "MegaCorp":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Bachman & Associates":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Blade Industries":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "NWO":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Clarke Incorporated":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "OmniTek Incorporated":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Four Sigma":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "KuaiGong International":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Fulcrum Secret Technologies":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "inline";
break;
case "BitRunners":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
break;
case "The Black Hand":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "NiteSec":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
break;
case "Chongqing":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Sector-12":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "New Tokyo":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Aevum":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Ishima":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Volhaven":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Speakers for the Dead":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "The Dark Army":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "The Syndicate":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Silhouette":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "none";
break;
case "Tetrads":
hackDiv.style.display = "none";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Slum Snakes":
hackDiv.style.display = "none";
fieldWorkDiv.style.display = "inline";
securityWorkDiv.style.display = "inline";
break;
case "Netburners":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
break;
case "Tian Di Hui":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "inline";
break;
case "CyberSec":
hackDiv.style.display = "inline";
fieldWorkDiv.style.display = "none";
securityWorkDiv.style.display = "none";
break;
default:
console.log("Faction does not exist");
break;
}
} else {
console.log("Not a member of this faction, cannot display faction information");
}
}
function displayFactionAugmentations(factionName) {
document.getElementById("faction-augmentations-page-desc").innerHTML = "Lists all augmentations that are available to purchase from " + factionName;
var faction = Factions[factionName];
var augmentationsList = document.getElementById("faction-augmentations-list");
while (augmentationsList.firstChild) {
augmentationsList.removeChild(augmentationsList.firstChild);
}
for (var i = 0; i < faction.augmentations.length; ++i) {
(function () {
var aug = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][faction.augmentations[i]];
if (aug == null) {
console.log("ERROR: Invalid Augmentation");
return;
}
var owned = false;
for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations.length; ++j) {
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations[j].name == aug.name) {
owned = true;
}
}
for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].augmentations.length; ++j) {
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].augmentations[j].name == aug.name) {
owned = true;
}
}
var item = document.createElement("li");
var span = document.createElement("span");
var aDiv = document.createElement("div");
var aElem = document.createElement("a");
var pElem = document.createElement("p");
aElem.setAttribute("href", "#");
var req = aug.baseRepRequirement * faction.augmentationRepRequirementMult;
if (aug.name != __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor && (aug.owned || owned)) {
aElem.setAttribute("class", "a-link-button-inactive");
pElem.innerHTML = "ALREADY OWNED";
} else if (faction.playerReputation >= req) {
aElem.setAttribute("class", "a-link-button");
pElem.innerHTML = "UNLOCKED - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(aug.baseCost * faction.augmentationPriceMult, 2);
} else {
aElem.setAttribute("class", "a-link-button-inactive");
pElem.innerHTML = "LOCKED (Requires " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(req, 1) + " faction reputation) - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(aug.baseCost * faction.augmentationPriceMult, 2);
pElem.style.color = "red";
}
aElem.style.display = "inline";
pElem.style.display = "inline";
aElem.innerHTML = aug.name;
if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
aElem.innerHTML += " - Level " + (getNextNeurofluxLevel());
}
span.style.display = "inline-block"
//The div will have the tooltip.
aDiv.setAttribute("class", "tooltip");
aDiv.innerHTML = '<span class="tooltiptext">' + aug.info + " </span>";
aDiv.appendChild(aElem);
aElem.addEventListener("click", function() {
purchaseAugmentationBoxCreate(aug, faction);
});
span.appendChild(aDiv);
span.appendChild(pElem);
item.appendChild(span);
augmentationsList.appendChild(item);
}()); //Immediate invocation closure
}
}
function purchaseAugmentationBoxCreate(aug, fac) {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
yesBtn.innerHTML = "Purchase";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
purchaseAugmentation(aug, fac);
});
noBtn.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("<h2>aug.name</h2><br>" +
aug.info + "<br><br>" +
"<br>Would you like to purchase the " + aug.name + " Augmentation for $" +
Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(aug.baseCost * fac.augmentationPriceMult, 2) + "?");
}
function purchaseAugmentation(aug, fac, sing=false) {
if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].Targeting2 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].Targeting1].owned == false) {
var txt = "You must first install Augmented Targeting I before you can upgrade it to Augmented Targeting II";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].Targeting3 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].Targeting2].owned == false) {
var txt = "You must first install Augmented Targeting II before you can upgrade it to Augmented Targeting III";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].CombatRib2 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].CombatRib1].owned == false) {
var txt = "You must first install Combat Rib I before you can upgrade it to Combat Rib II";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].CombatRib3 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].CombatRib2].owned == false) {
var txt = "You must first install Combat Rib II before you can upgrade it to Combat Rib III";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].GrapheneBionicSpine &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].BionicSpine].owned == false) {
var txt = "You must first install a Bionic Spine before you can upgrade it to a Graphene Bionic Spine";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].GrapheneBionicLegs &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].BionicLegs].owned == false) {
var txt = "You must first install Bionic Legs before you can upgrade it to Graphene Bionic Legs";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMCoreV2 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMCore].owned == false) {
var txt = "You must first install Embedded Netburner Module Core Implant before you can upgrade it to V2";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMCoreV3 &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMCoreV2].owned == false) {
var txt = "You must first install Embedded Netburner Module Core V2 Upgrade before you can upgrade it to V3";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if ((aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMCore ||
aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMAnalyzeEngine ||
aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENMDMA) &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].ENM].owned == false) {
var txt = "You must first install the Embedded Netburner Module before installing any upgrades to it";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if ((aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].PCDNIOptimizer ||
aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].PCDNINeuralNetwork) &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].PCDNI].owned == false) {
var txt = "You must first install the Pc Direct-Neural Interface before installing this upgrade";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].GrapheneBrachiBlades &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].BrachiBlades].owned == false) {
var txt = "You must first install the Brachi Blades augmentation before installing this upgrade";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].GrapheneBionicArms &&
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].BionicArms].owned == false) {
var txt = "You must first install the Bionic Arms augmentation before installing this upgrade";
if (sing) {return txt;} else {Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);}
} else if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].money.gte(aug.baseCost * fac.augmentationPriceMult)) {
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].firstAugPurchased = true;
var queuedAugmentation = new __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["d" /* PlayerOwnedAugmentation */](aug.name);
if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
queuedAugmentation.level = getNextNeurofluxLevel();
}
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations.push(queuedAugmentation);
__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].loseMoney((aug.baseCost * fac.augmentationPriceMult));
//If you just purchased Neuroflux Governor, recalculate the cost
if (aug.name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
var nextLevel = getNextNeurofluxLevel();
--nextLevel;
var mult = Math.pow(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].NeuroFluxGovernorLevelMult, nextLevel);
aug.setRequirements(500 * mult, 750000 * mult);
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations.length-1; ++i) {
aug.baseCost *= __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MultipleAugMultiplier;
}
}
for (var name in __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */]) {
if (__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */].hasOwnProperty(name)) {
__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][name].baseCost *= __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MultipleAugMultiplier;
}
}
if (sing) {
return "You purchased " + aug.name;
} else {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You purchased " + aug.name + ". It's enhancements will not take " +
"effect until they are installed. To install your augmentations, go to the " +
"'Augmentations' tab on the left-hand navigation menu. Purchasing additional " +
"augmentations will now be more expensive.");
}
displayFactionAugmentations(fac.name);
} else {
if (sing) {
return "You don't have enough money to purchase " + aug.name;
} else {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You don't have enough money to purchase this Augmentation!");
}
}
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
}
function getNextNeurofluxLevel() {
var aug = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor];
if (aug == null) {
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].augmentations.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].augmentations[i].name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
aug = __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].augmentations[i];
}
}
if (aug == null) {
console.log("ERROR, Could not find NeuroFlux Governor aug");
return 1;
}
}
var nextLevel = aug.level + 1;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].queuedAugmentations[i].name == __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].NeuroFluxGovernor) {
++nextLevel;
}
}
return nextLevel;
}
function processPassiveFactionRepGain(numCycles) {
var numTimesGain = (numCycles / 600) * __WEBPACK_IMPORTED_MODULE_6__Player_js__["a" /* Player */].faction_rep_mult;
for (var name in Factions) {
if (Factions.hasOwnProperty(name)) {
var faction = Factions[name];
//TODO Get hard value of 1 rep per "rep gain cycle"" for now..
//maybe later make this based on
//a player's 'status' like how powerful they are and how much money they have
if (faction.isMember) {faction.playerReputation += (numTimesGain * __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["a" /* BitNodeMultipliers */].FactionPassiveRepGain);}
}
}
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SpecialServerNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SpecialServerIps; });
/* unused harmony export SpecialServerIpsMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadSpecialServerIps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeSpecialServerIps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initSpecialServerIps; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_JSONReviver_js__ = __webpack_require__(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(__WEBPACK_IMPORTED_MODULE_0__utils_JSONReviver_js__["b" /* Generic_toJSON */])("SpecialServerIpsMap", this);
}
SpecialServerIpsMap.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_0__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(SpecialServerIpsMap, value.data);
}
__WEBPACK_IMPORTED_MODULE_0__utils_JSONReviver_js__["c" /* 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, __WEBPACK_IMPORTED_MODULE_0__utils_JSONReviver_js__["c" /* Reviver */]);
}
function initSpecialServerIps() {
SpecialServerIps = new SpecialServerIpsMap();
}
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Locations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return displayLocationContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initLocationButtons; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Crimes_js__ = __webpack_require__(40);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Infiltration_js__ = __webpack_require__(51);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__ServerPurchases_js__ = __webpack_require__(55);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__utils_IPAddress_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__ = __webpack_require__(20);
/* Display Location Content when visiting somewhere in the World*/
let Locations = {
//Cities
Aevum: "Aevum",
//AevumDesc: ""
Chongqing: "Chongqing",
Sector12: "Sector-12",
NewTokyo: "New Tokyo",
Ishima: "Ishima",
Volhaven: "Volhaven",
//Aevum Locations
AevumTravelAgency: "Aevum Travel Agency",
AevumSummitUniversity: "Summit University",
AevumECorp: "ECorp",
AevumBachmanAndAssociates: "Bachman & Associates",
AevumClarkeIncorporated: "Clarke Incorporated",
AevumFulcrumTechnologies: "Fulcrum Technolgies",
AevumAeroCorp: "AeroCorp",
AevumGalacticCybersystems: "Galactic Cybersystems",
AevumWatchdogSecurity: "Watchdog Security",
AevumRhoConstruction: "Rho Construction",
AevumPolice: "Aevum Police Headquarters",
AevumNetLinkTechnologies: "NetLink Technologies",
AevumCrushFitnessGym: "Crush Fitness Gym",
AevumSnapFitnessGym: "Snap Fitness Gym",
AevumSlums: "Aevum Slums",
//Chongqing locations
ChongqingTravelAgency: "Chongqing Travel Agency",
ChongqingKuaiGongInternational: "KuaiGong International",
ChongqingSolarisSpaceSystems: "Solaris Space Systems",
ChongqingSlums: "Chongqing Slums",
//Sector 12
Sector12TravelAgency: "Sector-12 Travel Agency",
Sector12RothmanUniversity: "Rothman University",
Sector12MegaCorp: "MegaCorp",
Sector12BladeIndustries: "Blade Industries",
Sector12FourSigma: "Four Sigma",
Sector12IcarusMicrosystems: "Icarus Microsystems",
Sector12UniversalEnergy: "Universal Energy",
Sector12DeltaOne: "DeltaOne",
Sector12CIA: "Central Intelligence Agency",
Sector12NSA: "National Security Agency",
Sector12AlphaEnterprises: "Alpha Enterprises",
Sector12CarmichaelSecurity: "Carmichael Security",
Sector12FoodNStuff: "FoodNStuff",
Sector12JoesGuns: "Joe's Guns",
Sector12IronGym: "Iron Gym",
Sector12PowerhouseGym: "Powerhouse Gym",
Sector12Slums: "Sector-12 Slums",
//New Tokyo
NewTokyoTravelAgency: "New Tokyo Travel Agency",
NewTokyoDefComm: "DefComm",
NewTokyoVitaLife: "VitaLife",
NewTokyoGlobalPharmaceuticals: "Global Pharmaceuticals",
NewTokyoNoodleBar: "Noodle Bar",
NewTokyoSlums: "New Tokyo Slums",
//Ishima
IshimaTravelAgency: "Ishima Travel Agency",
IshimaStormTechnologies: "Storm Technologies",
IshimaNovaMedical: "Nova Medical",
IshimaOmegaSoftware: "Omega Software",
IshimaSlums: "Ishima Slums",
//Volhaven
VolhavenTravelAgency: "Volhaven Travel Agency",
VolhavenZBInstituteOfTechnology: "ZB Institute of Technology",
VolhavenOmniTekIncorporated: "OmniTek Incorporated",
VolhavenNWO: "NWO",
VolhavenHeliosLabs: "Helios Labs",
VolhavenOmniaCybersystems: "Omnia Cybersystems",
VolhavenLexoCorp: "LexoCorp",
VolhavenSysCoreSecurities: "SysCore Securities",
VolhavenCompuTek: "CompuTek",
VolhavenMilleniumFitnessGym: "Millenium Fitness Gym",
VolhavenSlums: "Volhaven Slums",
//Generic locations
Hospital: "Hospital",
WorldStockExchange: "World Stock Exchange",
}
function displayLocationContent() {
if (__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].debug) {
console.log("displayLocationContent() called with location " + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location)
}
var returnToWorld = document.getElementById("location-return-to-world-button");
var locationName = document.getElementById("location-name");
var locationInfo = document.getElementById("location-info");
var softwareJob = document.getElementById("location-software-job");
var softwareConsultantJob = document.getElementById("location-software-consultant-job")
var itJob = document.getElementById("location-it-job");
var securityEngineerJob = document.getElementById("location-security-engineer-job");
var networkEngineerJob = document.getElementById("location-network-engineer-job");
var businessJob = document.getElementById("location-business-job");
var businessConsultantJob = document.getElementById("location-business-consultant-job");
var securityJob = document.getElementById("location-security-job");
var agentJob = document.getElementById("location-agent-job");
var employeeJob = document.getElementById("location-employee-job");
var employeePartTimeJob = document.getElementById("location-parttime-employee-job");
var waiterJob = document.getElementById("location-waiter-job");
var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job");
var work = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-work");
var jobTitle = document.getElementById("location-job-title");
var jobReputation = document.getElementById("location-job-reputation");
var companyFavor = document.getElementById("location-company-favor");
var locationTxtDiv1 = document.getElementById("location-text-divider-1");
var locationTxtDiv2 = document.getElementById("location-text-divider-2");
var locationTxtDiv3 = document.getElementById("location-text-divider-3");
var gymTrainStr = document.getElementById("location-gym-train-str");
var gymTrainDef = document.getElementById("location-gym-train-def");
var gymTrainDex = document.getElementById("location-gym-train-dex");
var gymTrainAgi = document.getElementById("location-gym-train-agi");
var studyComputerScience = document.getElementById("location-study-computer-science");
var classDataStructures = document.getElementById("location-data-structures-class");
var classNetworks = document.getElementById("location-networks-class");
var classAlgorithms = document.getElementById("location-algorithms-class");
var classManagement = document.getElementById("location-management-class");
var classLeadership = document.getElementById("location-leadership-class");
var purchase2gb = document.getElementById("location-purchase-2gb");
var purchase4gb = document.getElementById("location-purchase-4gb");
var purchase8gb = document.getElementById("location-purchase-8gb");
var purchase16gb = document.getElementById("location-purchase-16gb");
var purchase32gb = document.getElementById("location-purchase-32gb");
var purchase64gb = document.getElementById("location-purchase-64gb");
var purchase128gb = document.getElementById("location-purchase-128gb");
var purchase256gb = document.getElementById("location-purchase-256gb");
var purchase512gb = document.getElementById("location-purchase-512gb");
var purchase1tb = document.getElementById("location-purchase-1tb");
var purchaseTor = document.getElementById("location-purchase-tor");
var purchaseHomeRam = document.getElementById("location-purchase-home-ram");
var travelAgencyText = document.getElementById("location-travel-agency-text");
var travelToAevum = document.getElementById("location-travel-to-aevum");
var travelToChongqing = document.getElementById("location-travel-to-chongqing");
var travelToSector12 = document.getElementById("location-travel-to-sector12");
var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo");
var travelToIshima = document.getElementById("location-travel-to-ishima");
var travelToVolhaven = document.getElementById("location-travel-to-volhaven");
var infiltrate = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-infiltrate");
var hospitalTreatment = document.getElementById("location-hospital-treatment");
var slumsDescText = document.getElementById("location-slums-description");
var slumsShoplift = document.getElementById("location-slums-shoplift");
var slumsRobStore = document.getElementById("location-slums-rob-store");
var slumsMug = document.getElementById("location-slums-mug");
var slumsLarceny = document.getElementById("location-slums-larceny");
var slumsDealDrugs = document.getElementById("location-slums-deal-drugs");
var slumsTrafficArms = document.getElementById("location-slums-traffic-arms");
var slumsHomicide = document.getElementById("location-slums-homicide");
var slumsGta = document.getElementById("location-slums-gta");
var slumsKidnap = document.getElementById("location-slums-kidnap");
var slumsAssassinate = document.getElementById("location-slums-assassinate");
var slumsHeist = document.getElementById("location-slums-heist");
var loc = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location;
returnToWorld.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadWorldContent();
});
locationName.innerHTML = loc;
locationName.style.display = "block";
locationInfo.style.display = "block";
softwareJob.style.display = "none";
softwareConsultantJob.style.display = "none";
itJob.style.display = "none";
securityEngineerJob.style.display = "none";
networkEngineerJob.style.display = "none";
businessJob.style.display = "none";
businessConsultantJob.style.display = "none";
securityJob.style.display = "none";
agentJob.style.display = "none";
employeeJob.style.display = "none";
employeePartTimeJob.style.display = "none";
waiterJob.style.display = "none";
waiterPartTimeJob.style.display = "none";
softwareJob.innerHTML = "Apply for Software Job";
softwareConsultantJob.innerHTML = "Apply for a Software Consultant job";
itJob.innerHTML = "Apply for IT Job";
securityEngineerJob.innerHTML = "Apply for Security Engineer Job";
networkEngineerJob.innerHTML = "Apply for Network Engineer Job";
businessJob.innerHTML = "Apply for Business Job";
businessConsultantJob.innerHTML = "Apply for a Business Consultant Job";
securityJob.innerHTML = "Apply for Security Job";
agentJob.innerHTML = "Apply for Agent Job";
employeeJob.innerHTML = "Apply to be an Employee";
employeePartTimeJob.innerHTML = "Apply to be a Part-time Employee";
waiterJob.innerHTML = "Apply to be a Waiter";
waiterPartTimeJob.innerHTML = "Apply to be a Part-time Waiter"
work.style.display = "none";
gymTrainStr.style.display = "none";
gymTrainDef.style.display = "none";
gymTrainDex.style.display = "none";
gymTrainAgi.style.display = "none";
studyComputerScience.style.display = "none";
classDataStructures.style.display = "none";
classNetworks.style.display = "none";
classAlgorithms.style.display = "none";
classManagement.style.display = "none";
classLeadership.style.display = "none";
purchase2gb.style.display = "none";
purchase4gb.style.display = "none";
purchase8gb.style.display = "none";
purchase16gb.style.display = "none";
purchase32gb.style.display = "none";
purchase64gb.style.display = "none";
purchase128gb.style.display = "none";
purchase256gb.style.display = "none";
purchase512gb.style.display = "none";
purchase1tb.style.display = "none";
purchaseTor.style.display = "none";
purchaseHomeRam.style.display = "none";
purchase2gb.innerHTML = "Purchase 2GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(2*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase4gb.innerHTML = "Purchase 4GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(4*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase8gb.innerHTML = "Purchase 8GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(8*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase16gb.innerHTML = "Purchase 16GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(16*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase32gb.innerHTML = "Purchase 32GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(32*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase64gb.innerHTML = "Purchase 64GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(64*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase128gb.innerHTML = "Purchase 128GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(128*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase256gb.innerHTML = "Purchase 256GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(256*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase512gb.innerHTML = "Purchase 512GB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(512*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchase1tb.innerHTML = "Purchase 1TB Server - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(1024*__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer, 2);
purchaseTor.innerHTML = "Purchase TOR Router - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].TorRouterCost, 2);
travelAgencyText.style.display = "none";
travelToAevum.style.display = "none";
travelToChongqing.style.display = "none";
travelToSector12.style.display = "none";
travelToNewTokyo.style.display = "none";
travelToIshima.style.display = "none";
travelToVolhaven.style.display = "none";
infiltrate.style.display = "none";
hospitalTreatment.style.display = "none";
slumsDescText.style.display = "none";
slumsShoplift.style.display = "none";
slumsRobStore.style.display = "none";
slumsMug.style.display = "none";
slumsLarceny.style.display = "none";
slumsDealDrugs.style.display = "none";
slumsTrafficArms.style.display = "none";
slumsHomicide.style.display = "none";
slumsGta.style.display = "none";
slumsKidnap.style.display = "none";
slumsAssassinate.style.display = "none";
slumsHeist.style.display = "none";
//Check if the player is employed at this Location. If he is, display the "Work" button,
//update the job title, etc.
if (loc == __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].companyName) {
var company = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc];
jobTitle.style.display = "block";
jobReputation.style.display = "inline";
companyFavor.style.display = "inline";
locationTxtDiv1.style.display = "block";
locationTxtDiv2.style.display = "block";
locationTxtDiv3.style.display = "block";
jobTitle.innerHTML = "Job Title: " + __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].companyPosition.positionName;
var repGain = company.getFavorGain();
if (repGain.length != 2) {repGain = 0;}
repGain = repGain[0];
jobReputation.innerHTML = "Company reputation: " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(company.playerReputation, 4) +
"<span class='tooltiptext'>You will earn " +
Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(repGain, 4) +
" faction favor upon resetting after installing an Augmentation</span>";
companyFavor.innerHTML = "Company Favor: " + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(company.favor, 4) +
"<span class='tooltiptext'>Company favor increases the rate at which " +
"you earn reputation for this company by 1% per favor. Company favor " +
"is gained whenever you reset after installing an Augmentation. The amount of " +
"favor you gain depends on how much reputation you have with the company</span>";
work.style.display = "block";
var currPos = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].companyPosition;
work.addEventListener("click", function() {
if (currPos.isPartTimeJob()) {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startWorkPartTime();
} else {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startWork();
}
return false;
});
//Change the text for the corresponding position from "Apply for X Job" to "Apply for promotion"
if (currPos.isSoftwareJob()) {
softwareJob.innerHTML = "Apply for a promotion (Software)";
} else if (currPos.isSoftwareConsultantJob()) {
softwareConsultantJob.innerHTML = "Apply for a promotion (Software Consultant)";
} else if (currPos.isITJob()) {
itJob.innerHTML = "Apply for a promotion (IT)";
} else if (currPos.isSecurityEngineerJob()) {
securityEngineerJob.innerHTML = "Apply for a promotion (Security Engineer)";
} else if (currPos.isNetworkEngineerJob()) {
networkEngineerJob.innerHTML = "Apply for a promotion (Network Engineer)";
} else if (currPos.isBusinessJob()) {
businessJob.innerHTML = "Apply for a promotion (Business)";
} else if (currPos.isBusinessConsultantJob()) {
businessConsultantJob.innerHTML = "Apply for a promotion (Business Consultant)";
} else if (currPos.isSecurityJob()) {
securityJob.innerHTML = "Apply for a promotion (Security)";
} else if (currPos.isAgentJob()) {
agentJob.innerHTML = "Apply for a promotion (Agent)";
}
} else {
jobTitle.style.display = "none";
jobReputation.style.display = "none";
companyFavor.style.display = "none";
locationTxtDiv1.style.display = "none";
locationTxtDiv2.style.display = "none";
locationTxtDiv3.style.display = "none";
}
//Calculate hospital Cost
if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp < 0) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp = 0;}
var hospitalTreatmentCost = (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].max_hp - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp) * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HospitalCostPerHp;
//Set tooltip for job requirements
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].SoftwareIntern, softwareJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].SoftwareConsultant, softwareConsultantJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].ITIntern, itJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].SecurityEngineer, securityEngineerJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].NetworkEngineer, networkEngineerJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].BusinessIntern, businessJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].BusinessConsultant, businessConsultantJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].SecurityGuard, securityJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].FieldAgent, agentJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].Employee, employeeJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].PartTimeEmployee, employeePartTimeJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].Waiter, waiterJob);
setJobRequirementTooltip(loc, __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].PartTimeWaiter, waiterPartTimeJob);
switch (loc) {
case Locations.AevumTravelAgency:
travelAgencyText.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case Locations.AevumSummitUniversity:
var costMult = 4, expMult = 3;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case Locations.AevumECorp:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumECorp,
6000, 116, 150, 9.5);
break;
case Locations.AevumBachmanAndAssociates:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumBachmanAndAssociates,
1500, 42, 60, 6.5);
break;
case Locations.AevumClarkeIncorporated:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumClarkeIncorporated,
2400, 34, 75, 6);
break;
case Locations.AevumFulcrumTechnologies:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumFulcrumTechnologies,
6000, 96, 100, 10);
break;
case Locations.AevumAeroCorp:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumAeroCorp,
2000, 32, 50, 7);
break;
case Locations.AevumGalacticCybersystems:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumGalacticCybersystems,
1400, 30, 50, 6);
break;
case Locations.AevumWatchdogSecurity:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumWatchdogSecurity,
850, 16, 30, 5);
break;
case Locations.AevumRhoConstruction:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumRhoConstruction,
600, 12, 20, 3);
break;
case Locations.AevumPolice:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumPolice,
700, 14, 25, 3.5);
break;
case Locations.AevumNetLinkTechnologies:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
purchase2gb.style.display = "block";
purchase4gb.style.display = "block";
purchase8gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.AevumNetLinkTechnologies,
160, 10, 15, 2);
break;
case Locations.AevumCrushFitnessGym:
var costMult = 2, expMult = 1.5;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case Locations.AevumSnapFitnessGym:
var costMult = 6, expMult = 4;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case Locations.ChongqingTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case Locations.ChongqingKuaiGongInternational:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.ChongqingKuaiGongInternational,
5500, 48, 100, 10);
break;
case Locations.ChongqingSolarisSpaceSystems:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.ChongqingSolarisSpaceSystems,
3600, 26, 75, 9.5);
break;
case Locations.Sector12TravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case Locations.Sector12RothmanUniversity:
var costMult = 3, expMult = 2;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case Locations.Sector12MegaCorp:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12MegaCorp,
6000, 114, 125, 11);
break;
case Locations.Sector12BladeIndustries:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12BladeIndustries,
3000, 46, 100, 7.5);
break;
case Locations.Sector12FourSigma:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12FourSigma,
1500, 58, 100, 11.5);
break;
case Locations.Sector12IcarusMicrosystems:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12IcarusMicrosystems,
900, 32, 70, 8.5);
break;
case Locations.Sector12UniversalEnergy:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12UniversalEnergy,
775, 24, 50, 7);
break;
case Locations.Sector12DeltaOne:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12DeltaOne,
1200, 38, 75, 7);
break;
case Locations.Sector12CIA:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12CIA,
1450, 44, 80, 8.5);
break;
case Locations.Sector12NSA:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12NSA,
1400, 40, 80, 8);
break;
case Locations.Sector12AlphaEnterprises:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
businessJob.style.display = "block";
purchase2gb.style.display = "block";
purchase4gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12AlphaEnterprises,
250, 14, 40, 3);
break;
case Locations.Sector12CarmichaelSecurity:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
agentJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12CarmichaelSecurity,
500, 18, 60, 3);
break;
case Locations.Sector12FoodNStuff:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
employeeJob.style.display = "block";
employeePartTimeJob.style.display = "block";
break;
case Locations.Sector12JoesGuns:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
employeeJob.style.display = "block";
employeePartTimeJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.Sector12JoesGuns,
120, 8, 20, 2.5);
break;
case Locations.Sector12IronGym:
var costMult = 1, expMult = 1;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case Locations.Sector12PowerhouseGym:
var costMult = 10, expMult = 7.5;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
case Locations.NewTokyoTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToIshima.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case Locations.NewTokyoDefComm:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.NewTokyoDefComm,
1300, 28, 70, 6);
break;
case Locations.NewTokyoVitaLife:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.NewTokyoVitaLife,
750, 22, 100, 5.5);
break;
case Locations.NewTokyoGlobalPharmaceuticals:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.NewTokyoGlobalPharmaceuticals,
900, 24, 80, 6);
break;
case Locations.NewTokyoNoodleBar:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
waiterJob.style.display = "block";
waiterPartTimeJob.style.display = "block";
break;
case Locations.IshimaTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToVolhaven.style.display = "block";
break;
case Locations.IshimaStormTechnologies:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "none";
agentJob.style.display = "none";
employeeJob.style.display = "none";
waiterJob.style.display = "none";
purchase32gb.style.display = "block";
purchase64gb.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.IshimaStormTechnologies,
700, 24, 100, 6.5);
break;
case Locations.IshimaNovaMedical:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.IshimaNovaMedical,
600, 20, 50, 5);
break;
case Locations.IshimaOmegaSoftware:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
businessJob.style.display = "block";
purchase4gb.style.display = "block";
purchase8gb.style.display = "block";
purchase16gb.style.display = "block";
purchase32gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.IshimaOmegaSoftware,
200, 10, 40, 2.5);
break;
case Locations.VolhavenTravelAgency:
travelAgencyText.style.display = "block";
travelToAevum.style.display = "block";
travelToChongqing.style.display = "block";
travelToSector12.style.display = "block";
travelToNewTokyo.style.display = "block";
travelToIshima.style.display = "block";
break;
case Locations.VolhavenZBInstituteOfTechnology:
var costMult = 5, expMult = 4;
displayUniversityLocationContent(costMult);
setUniversityLocationButtons(costMult, expMult);
break;
case Locations.VolhavenOmniTekIncorporated:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchase512gb.style.display = "block";
purchase1tb.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenOmniTekIncorporated,
1500, 44, 100, 7);
break;
case Locations.VolhavenNWO:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenNWO,
1800, 56, 200, 8);
break;
case Locations.VolhavenHeliosLabs:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenHeliosLabs,
1200, 28, 75, 6);
break;
case Locations.VolhavenOmniaCybersystems:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenOmniaCybersystems,
900, 28, 90, 6.5);
break;
case Locations.VolhavenLexoCorp:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
businessJob.style.display = "block";
securityJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenLexoCorp,
500, 14, 40, 3.5);
break;
case Locations.VolhavenSysCoreSecurities:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenSysCoreSecurities,
600, 16, 50, 4);
break;
case Locations.VolhavenCompuTek:
locationInfo.innerHTML = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc].info;
softwareJob.style.display = "block";
softwareConsultantJob.style.display = "block";
itJob.style.display = "block";
securityEngineerJob.style.display = "block";
networkEngineerJob.style.display = "block";
purchase8gb.style.display = "block";
purchase16gb.style.display = "block";
purchase32gb.style.display = "block";
purchase64gb.style.display = "block";
purchase128gb.style.display = "block";
purchase256gb.style.display = "block";
purchaseTor.style.display = "block";
purchaseHomeRam.style.display = "block";
setInfiltrateButton(infiltrate, Locations.VolhavenCompuTek,
300, 12, 35, 3.5);
break;
case Locations.VolhavenMilleniumFitnessGym:
var costMult = 3, expMult = 2.5;
displayGymLocationContent(costMult);
setGymLocationButtons(costMult, expMult);
break;
//All Slums
case Locations.AevumSlums:
case Locations.ChongqingSlums:
case Locations.Sector12Slums:
case Locations.NewTokyoSlums:
case Locations.IshimaSlums:
case Locations.VolhavenSlums:
var shopliftChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["u" /* determineCrimeChanceShoplift */])();
var robStoreChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["t" /* determineCrimeChanceRobStore */])();
var mugChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["s" /* determineCrimeChanceMug */])();
var larcenyChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["r" /* determineCrimeChanceLarceny */])();
var drugsChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["m" /* determineCrimeChanceDealDrugs */])();
var armsChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["v" /* determineCrimeChanceTraffickArms */])();
var homicideChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["p" /* determineCrimeChanceHomicide */])();
var gtaChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["n" /* determineCrimeChanceGrandTheftAuto */])();
var kidnapChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["q" /* determineCrimeChanceKidnap */])();
var assassinateChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["l" /* determineCrimeChanceAssassination */])();
var heistChance = Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["o" /* determineCrimeChanceHeist */])();
slumsDescText.style.display = "block";
slumsShoplift.style.display = "block";
slumsShoplift.innerHTML = "Shoplift (" + (shopliftChance*100).toFixed(3) + "% chance of success)";
slumsShoplift.innerHTML += '<span class="tooltiptext"> Attempt to shoplift from a low-end retailer </span>';
slumsRobStore.style.display = "block";
slumsRobStore.innerHTML = "Rob store(" + (robStoreChance*100).toFixed(3) + "% chance of success)";
slumsRobStore.innerHTML += '<span class="tooltiptext">Attempt to commit armed robbery on a high-end store </span>';
slumsMug.style.display = "block";
slumsMug.innerHTML = "Mug someone (" + (mugChance*100).toFixed(3) + "% chance of success)";
slumsMug.innerHTML += '<span class="tooltiptext"> Attempt to mug a random person on the street </span>';
slumsLarceny.style.display = "block";
slumsLarceny.innerHTML = "Larceny (" + (larcenyChance*100).toFixed(3) + "% chance of success)";
slumsLarceny.innerHTML +="<span class='tooltiptext'> Attempt to rob property from someone's house </span>";
slumsDealDrugs.style.display = "block";
slumsDealDrugs.innerHTML = "Deal Drugs (" + (drugsChance*100).toFixed(3) + "% chance of success)";
slumsDealDrugs.innerHTML += '<span class="tooltiptext"> Attempt to deal drugs </span>';
slumsTrafficArms.style.display = "block";
slumsTrafficArms.innerHTML = "Traffick Illegal Arms (" + (armsChance*100).toFixed(3) + "% chance of success)";
slumsTrafficArms.innerHTML += '<span class="tooltiptext"> Attempt to smuggle illegal arms into the city and sell them to gangs and criminal organizations </span>';
slumsHomicide.style.display = "block";
slumsHomicide.innerHTML = "Homicide (" + (homicideChance*100).toFixed(3) + "% chance of success)";
slumsHomicide.innerHTML += '<span class="tooltiptext"> Attempt to murder a random person on the street</span>';
slumsGta.style.display = "block";
slumsGta.innerHTML = "Grand Theft Auto (" + (gtaChance*100).toFixed(3) + "% chance of success)";
slumsGta.innerHTML += '<span class="tooltiptext"> Attempt to commit grand theft auto </span>';
slumsKidnap.style.display = "block";
slumsKidnap.innerHTML = "Kidnap and Ransom (" + (kidnapChance*100).toFixed(3) + "% chance of success)";
slumsKidnap.innerHTML += '<span class="tooltiptext"> Attempt to kidnap and ransom a high-profile target </span>';
slumsAssassinate.style.display = "block";
slumsAssassinate.innerHTML = "Assassinate (" + (assassinateChance*100).toFixed(3) + "% chance of success)";
slumsAssassinate.innerHTML += '<span class="tooltiptext"> Attempt to assassinate a high-profile target </span>';
slumsHeist.style.display = "block";
slumsHeist.innerHTML = "Heist (" + (heistChance*100).toFixed(3) + "% chance of success)";
slumsHeist.innerHTML += '<span class="tooltiptext"> Attempt to pull off the ultimate heist </span>';
break;
//Hospital
case Locations.Hospital:
hospitalTreatment.innerText = "Get treatment for wounds - $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(hospitalTreatmentCost, 2).toString();
hospitalTreatment.style.display = "block";
break;
default:
console.log("ERROR: INVALID LOCATION");
}
//Make the "Apply to be Employee and Waiter" texts disappear if you already hold the job
//Includes part-time stuff
if (loc == __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].companyName) {
var currPos = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].companyPosition;
if (currPos.positionName == __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].Employee.positionName) {
employeeJob.style.display = "none";
} else if (currPos.positionName == __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].Waiter.positionName) {
waiterJob.style.display = "none";
} else if (currPos.positionName == __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].PartTimeEmployee.positionName) {
employeePartTimeJob.style.display = "none";
} else if (currPos.positionName == __WEBPACK_IMPORTED_MODULE_0__Company_js__["d" /* CompanyPositions */].PartTimeWaiter.positionName) {
waiterPartTimeJob.style.display = "none";
}
}
}
function initLocationButtons() {
//Buttons to travel to different locations in World
let aevumTravelAgency = document.getElementById("aevum-travelagency");
aevumTravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumTravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumHospital = document.getElementById("aevum-hospital");
aevumHospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumSummitUniversity = document.getElementById("aevum-summituniversity");
aevumSummitUniversity.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumSummitUniversity;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumECorp = document.getElementById("aevum-ecorp");
aevumECorp.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumECorp;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumBachmanAndAssociates = document.getElementById("aevum-bachmanandassociates");
aevumBachmanAndAssociates.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumBachmanAndAssociates;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumClarkeIncorporated = document.getElementById("aevum-clarkeincorporated");
aevumClarkeIncorporated.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumClarkeIncorporated;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumFulcrumTechnologies = document.getElementById("aevum-fulcrumtechnologies");
aevumFulcrumTechnologies.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumFulcrumTechnologies;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumAeroCorp = document.getElementById("aevum-aerocorp");
aevumAeroCorp.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumAeroCorp;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumGalacticCybersystems = document.getElementById("aevum-galacticcybersystems");
aevumGalacticCybersystems.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumGalacticCybersystems;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumWatchdogSecurity = document.getElementById("aevum-watchdogsecurity");
aevumWatchdogSecurity.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumWatchdogSecurity;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumRhoConstruction = document.getElementById("aevum-rhoconstruction");
aevumRhoConstruction.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumRhoConstruction;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumPolice = document.getElementById("aevum-aevumpolice");
aevumPolice.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumPolice;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumNetLinkTechnologies = document.getElementById("aevum-netlinktechnologies");
aevumNetLinkTechnologies.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumNetLinkTechnologies;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumCrushFitnessGym = document.getElementById("aevum-crushfitnessgym");
aevumCrushFitnessGym.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumCrushFitnessGym;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumSnapFitnessGym = document.getElementById("aevum-snapfitnessgym");
aevumSnapFitnessGym.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumSnapFitnessGym;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let aevumSlums = document.getElementById("aevum-slums");
aevumSlums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.AevumSlums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let chongqingTravelAgency = document.getElementById("chongqing-travelagency");
chongqingTravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.ChongqingTravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let chongqingHospital = document.getElementById("chongqing-hospital");
chongqingHospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let chongqingKuaiGongInternational = document.getElementById("chongqing-kuaigonginternational");
chongqingKuaiGongInternational.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.ChongqingKuaiGongInternational;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let chongqingSolarisSpaceSystems = document.getElementById("chongqing-solarisspacesystems");
chongqingSolarisSpaceSystems.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.ChongqingSolarisSpaceSystems;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let chongqingSlums = document.getElementById("chongqing-slums");
chongqingSlums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.ChongqingSlums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12TravelAgency = document.getElementById("sector12-travelagency");
sector12TravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12TravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12Hospital = document.getElementById("sector12-hospital");
sector12Hospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12RothmanUniversity = document.getElementById("sector12-rothmanuniversity");
sector12RothmanUniversity.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12RothmanUniversity;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12MegaCorp = document.getElementById("sector12-megacorp");
sector12MegaCorp.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12MegaCorp;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12BladeIndustries = document.getElementById("sector12-bladeindustries");
sector12BladeIndustries.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12BladeIndustries;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12FourSigma = document.getElementById("sector12-foursigma");
sector12FourSigma.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12FourSigma;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12IcarusMicrosystems = document.getElementById("sector12-icarusmicrosystems");
sector12IcarusMicrosystems.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12IcarusMicrosystems;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12UniversalEnergy = document.getElementById("sector12-universalenergy");
sector12UniversalEnergy.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12UniversalEnergy;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12DeltaOne = document.getElementById("sector12-deltaone");
sector12DeltaOne.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12DeltaOne;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12CIA = document.getElementById("sector12-cia");
sector12CIA.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12CIA;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12NSA = document.getElementById("sector12-nsa");
sector12NSA.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12NSA;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12AlphaEnterprises = document.getElementById("sector12-alphaenterprises");
sector12AlphaEnterprises.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12AlphaEnterprises;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12CarmichaelSecurity = document.getElementById("sector12-carmichaelsecurity");
sector12CarmichaelSecurity.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12CarmichaelSecurity;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12FoodNStuff = document.getElementById("sector12-foodnstuff");
sector12FoodNStuff.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12FoodNStuff;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12JoesGuns = document.getElementById("sector12-joesguns");
sector12JoesGuns.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12JoesGuns;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12IronGym = document.getElementById("sector12-irongym");
sector12IronGym.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12IronGym;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12PowerhouseGym = document.getElementById("sector12-powerhousegym");
sector12PowerhouseGym.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12PowerhouseGym;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let sector12Slums = document.getElementById("sector12-slums");
sector12Slums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Sector12Slums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoTravelAgency = document.getElementById("newtokyo-travelagency");
newTokyoTravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoTravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoHospital = document.getElementById("newtokyo-hospital");
newTokyoHospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoDefComm = document.getElementById("newtokyo-defcomm");
newTokyoDefComm.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoDefComm;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoVitaLife = document.getElementById("newtokyo-vitalife");
newTokyoVitaLife.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoVitaLife;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoGlobalPharmaceuticals = document.getElementById("newtokyo-globalpharmaceuticals");
newTokyoGlobalPharmaceuticals.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoGlobalPharmaceuticals;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoNoodleBar = document.getElementById("newtokyo-noodlebar");
newTokyoNoodleBar.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoNoodleBar;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let newTokyoSlums = document.getElementById("newtokyo-slums");
newTokyoSlums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.NewTokyoSlums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaTravelAgency = document.getElementById("ishima-travelagency");
ishimaTravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.IshimaTravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaHospital = document.getElementById("ishima-hospital");
ishimaHospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaStormTechnologies = document.getElementById("ishima-stormtechnologies");
ishimaStormTechnologies.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.IshimaStormTechnologies;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaNovaMedical = document.getElementById("ishima-novamedical");
ishimaNovaMedical.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.IshimaNovaMedical;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaOmegaSoftware = document.getElementById("ishima-omegasoftware");
ishimaOmegaSoftware.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.IshimaOmegaSoftware;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let ishimaSlums = document.getElementById("ishima-slums");
ishimaSlums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.IshimaSlums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenTravelAgency = document.getElementById("volhaven-travelagency");
volhavenTravelAgency.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenTravelAgency;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenHospital = document.getElementById("volhaven-hospital");
volhavenHospital.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.Hospital;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenZBInstituteOfTechnology = document.getElementById("volhaven-zbinstituteoftechnology");
volhavenZBInstituteOfTechnology.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenZBInstituteOfTechnology;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenOmniTekIncorporated = document.getElementById("volhaven-omnitekincorporated");
volhavenOmniTekIncorporated.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenOmniTekIncorporated;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenNWO = document.getElementById("volhaven-nwo");
volhavenNWO.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenNWO;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenHeliosLabs = document.getElementById("volhaven-helioslabs");
volhavenHeliosLabs.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenHeliosLabs;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenOmniaCybersystems = document.getElementById("volhaven-omniacybersystems");
volhavenOmniaCybersystems.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenOmniaCybersystems;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenLexoCorp = document.getElementById("volhaven-lexocorp");
volhavenLexoCorp.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenLexoCorp;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenSysCoreSecurities = document.getElementById("volhaven-syscoresecurities");
volhavenSysCoreSecurities.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenSysCoreSecurities;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenCompuTek = document.getElementById("volhaven-computek");
volhavenCompuTek.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenCompuTek;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenMilleniumFitnessGym = document.getElementById("volhaven-milleniumfitnessgym");
volhavenMilleniumFitnessGym.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenMilleniumFitnessGym;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let volhavenSlums = document.getElementById("volhaven-slums");
volhavenSlums.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.VolhavenSlums;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadLocationContent();
return false;
});
let worldStockExchange = document.getElementById("generic-location-wse");
worldStockExchange.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].location = Locations.WorldStockExchange;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadStockMarketContent();
return false;
});
//Buttons to interact at a location (apply for job/promotion, train, purchase, etc.)
var softwareJob = document.getElementById("location-software-job");
var softwareConsultantJob = document.getElementById("location-software-consultant-job")
var itJob = document.getElementById("location-it-job");
var securityEngineerJob = document.getElementById("location-security-engineer-job");
var networkEngineerJob = document.getElementById("location-network-engineer-job");
var businessJob = document.getElementById("location-business-job");
var businessConsultantJob = document.getElementById("location-business-consultant-job");
var securityJob = document.getElementById("location-security-job");
var agentJob = document.getElementById("location-agent-job");
var employeeJob = document.getElementById("location-employee-job");
var employeePartTimeJob = document.getElementById("location-parttime-employee-job");
var waiterJob = document.getElementById("location-waiter-job");
var waiterPartTimeJob = document.getElementById("location-parttime-waiter-job");
var work = document.getElementById("location-work");
var purchase2gb = document.getElementById("location-purchase-2gb");
var purchase4gb = document.getElementById("location-purchase-4gb");
var purchase8gb = document.getElementById("location-purchase-8gb");
var purchase16gb = document.getElementById("location-purchase-16gb");
var purchase32gb = document.getElementById("location-purchase-32gb");
var purchase64gb = document.getElementById("location-purchase-64gb");
var purchase128gb = document.getElementById("location-purchase-128gb");
var purchase256gb = document.getElementById("location-purchase-256gb");
var purchase512gb = document.getElementById("location-purchase-512gb");
var purchase1tb = document.getElementById("location-purchase-1tb");
var purchaseTor = document.getElementById("location-purchase-tor");
var purchaseHomeRam = document.getElementById("location-purchase-home-ram");
var travelToAevum = document.getElementById("location-travel-to-aevum");
var travelToChongqing = document.getElementById("location-travel-to-chongqing");
var travelToSector12 = document.getElementById("location-travel-to-sector12");
var travelToNewTokyo = document.getElementById("location-travel-to-newtokyo");
var travelToIshima = document.getElementById("location-travel-to-ishima");
var travelToVolhaven = document.getElementById("location-travel-to-volhaven");
var slumsShoplift = document.getElementById("location-slums-shoplift");
var slumsRobStore = document.getElementById("location-slums-rob-store");
var slumsMug = document.getElementById("location-slums-mug");
var slumsLarceny = document.getElementById("location-slums-larceny");
var slumsDealDrugs = document.getElementById("location-slums-deal-drugs");
var slumsTrafficArms = document.getElementById("location-slums-traffic-arms");
var slumsHomicide = document.getElementById("location-slums-homicide");
var slumsGta = document.getElementById("location-slums-gta");
var slumsKidnap = document.getElementById("location-slums-kidnap");
var slumsAssassinate = document.getElementById("location-slums-assassinate");
var slumsHeist = document.getElementById("location-slums-heist");
var hospitalTreatment = document.getElementById("location-hospital-treatment");
softwareJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForSoftwareJob();
return false;
});
softwareConsultantJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForSoftwareConsultantJob();
return false;
});
itJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForItJob();
return false;
});
securityEngineerJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForSecurityEngineerJob();
return false;
});
networkEngineerJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForNetworkEngineerJob();
return false;
});
businessJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForBusinessJob();
return false;
});
businessConsultantJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForBusinessConsultantJob();
return false;
});
securityJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForSecurityJob();
return false;
});
agentJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForAgentJob();
return false;
});
employeeJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForEmployeeJob();
return false;
});
employeePartTimeJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForPartTimeEmployeeJob();
return false;
});
waiterJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForWaiterJob();
return false;
});
waiterPartTimeJob.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].applyForPartTimeWaiterJob();
return false;
});
purchase2gb.addEventListener("click", function() {
purchaseServerBoxCreate(2, 2 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase4gb.addEventListener("click", function() {
purchaseServerBoxCreate(4, 4 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase8gb.addEventListener("click", function() {
purchaseServerBoxCreate(8, 8 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase16gb.addEventListener("click", function() {
purchaseServerBoxCreate(16, 16 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase32gb.addEventListener("click", function() {
purchaseServerBoxCreate(32, 32 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase64gb.addEventListener("click", function() {
purchaseServerBoxCreate(64, 64 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase128gb.addEventListener("click", function() {
purchaseServerBoxCreate(128, 128 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase256gb.addEventListener("click", function() {
purchaseServerBoxCreate(256, 256 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase512gb.addEventListener("click", function() {
purchaseServerBoxCreate(512, 512 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchase1tb.addEventListener("click", function() {
purchaseServerBoxCreate(1024, 1024 * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer);
return false;
});
purchaseTor.addEventListener("click", function() {
purchaseTorRouter();
return false;
});
purchaseHomeRam.addEventListener("click", function() {
//Calculate how many times ram has been upgraded (doubled)
var currentRam = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].getHomeComputer().maxRam;
var newRam = currentRam * 2;
var numUpgrades = Math.log2(currentRam);
//Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded
var cost = currentRam * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome;
var mult = Math.pow(1.55, numUpgrades);
cost = cost * mult;
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
yesBtn.innerHTML = "Purchase"; noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", ()=>{
Object(__WEBPACK_IMPORTED_MODULE_7__ServerPurchases_js__["a" /* purchaseRamForHomeComputer */])(cost);
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
noBtn.addEventListener("click", ()=>{
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("Would you like to purchase additional RAM for your home computer? <br><br>" +
"This will upgrade your RAM from " + currentRam + "GB to " + newRam + "GB. <br><br>" +
"This will cost $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2));
});
travelToAevum.addEventListener("click", function() {
travelBoxCreate(Locations.Aevum, 200000);
return false;
});
travelToChongqing.addEventListener("click", function() {
travelBoxCreate(Locations.Chongqing, 200000);
return false;
});
travelToSector12.addEventListener("click", function() {
travelBoxCreate(Locations.Sector12, 200000);
return false;
});
travelToNewTokyo.addEventListener("click", function() {
travelBoxCreate(Locations.NewTokyo, 200000);
return false;
});
travelToIshima.addEventListener("click", function() {
travelBoxCreate(Locations.Ishima, 200000);
return false;
});
travelToVolhaven.addEventListener("click", function() {
travelBoxCreate(Locations.Volhaven, 200000);
return false;
});
slumsShoplift.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["j" /* commitShopliftCrime */])();
return false;
});
slumsRobStore.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["i" /* commitRobStoreCrime */])();
return false;
});
slumsMug.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["h" /* commitMugCrime */])();
return false;
});
slumsLarceny.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["g" /* commitLarcenyCrime */])();
return false;
});
slumsDealDrugs.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["b" /* commitDealDrugsCrime */])();
return false;
});
slumsTrafficArms.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["k" /* commitTraffickArmsCrime */])();
return false;
});
slumsHomicide.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["e" /* commitHomicideCrime */])();
return false;
});
slumsGta.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["c" /* commitGrandTheftAutoCrime */])();
return false;
});
slumsKidnap.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["f" /* commitKidnapCrime */])();
return false;
});
slumsAssassinate.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["a" /* commitAssassinationCrime */])();
return false;
});
slumsHeist.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_2__Crimes_js__["d" /* commitHeistCrime */])();
return false;
});
hospitalTreatment.addEventListener("click", function() {
if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp < 0) {__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp = 0;}
var price = (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].max_hp - __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp) * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HospitalCostPerHp;
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(price);
Object(__WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You were healed to full health! The hospital billed " +
"you for $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(price, 2).toString());
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].hp = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].max_hp;
displayLocationContent();
return false;
});
}
function travelToCity(destCityName, cost) {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].firstTimeTraveled = true;
if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(cost)) {
Object(__WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You cannot afford to travel to " + destCityName);
return;
}
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(cost);
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].city = destCityName;
Object(__WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You are now in " + destCityName + "!");
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadWorldContent();
}
function purchaseTorRouter() {
if (__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].money.lt(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].TorRouterCost)) {
Object(__WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You cannot afford to purchase the Tor router");
return;
}
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].TorRouterCost);
var darkweb = new __WEBPACK_IMPORTED_MODULE_6__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_11__utils_IPAddress_js__["a" /* createRandomIp */])(), "darkweb", "", false, false, false, 1);
Object(__WEBPACK_IMPORTED_MODULE_6__Server_js__["a" /* AddToAllServers */])(darkweb);
__WEBPACK_IMPORTED_MODULE_8__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp("Darkweb Server", darkweb.ip);
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive");
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].getHomeComputer().ip);
Object(__WEBPACK_IMPORTED_MODULE_9__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You have purchased a Tor router!<br>You now have access to the dark web from your home computer<br>Use the scan/netstat commands to search for the dark web connection.");
}
function displayUniversityLocationContent(costMult) {
var studyComputerScienceButton = document.getElementById("location-study-computer-science");
var classDataStructuresButton = document.getElementById("location-data-structures-class");
var classNetworksButton = document.getElementById("location-networks-class");
var classAlgorithmsButton = document.getElementById("location-algorithms-class");
var classManagementButton = document.getElementById("location-management-class");
var classLeadershipButton = document.getElementById("location-leadership-class");
studyComputerScienceButton.style.display = "block";
classDataStructuresButton.style.display = "block";
classNetworksButton.style.display = "block";
classAlgorithmsButton.style.display = "block";
classManagementButton.style.display = "block";
classLeadershipButton.style.display = "block";
//Costs (per second)
var dataStructuresCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassDataStructuresBaseCost * costMult;
var networksCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassNetworksBaseCost * costMult;
var algorithmsCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassAlgorithmsBaseCost * costMult;
var managementCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassManagementBaseCost * costMult;
var leadershipCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassLeadershipBaseCost * costMult;
//Update button text to show cost
classDataStructuresButton.innerHTML = "Take Data Structures course ($" + dataStructuresCost + " / sec)";
classNetworksButton.innerHTML = "Take Networks course ($" + networksCost + " / sec)";
classAlgorithmsButton.innerHTML = "Take Algorithms course ($" + algorithmsCost + " / sec)";
classManagementButton.innerHTML = "Take Management course ($" + managementCost + " / sec)";
classLeadershipButton.innerHTML = "Take Leadership course ($" + leadershipCost + " / sec)";
}
function setUniversityLocationButtons(costMult, expMult) {
var newStudyCS = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-study-computer-science");
newStudyCS.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassStudyComputerScience);
return false;
});
var newClassDataStructures = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-data-structures-class");
newClassDataStructures.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassDataStructures);
return false;
});
var newClassNetworks = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-networks-class");
newClassNetworks.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassNetworks);
return false;
});
var newClassAlgorithms = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-algorithms-class");
newClassAlgorithms.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassAlgorithms);
return false;
});
var newClassManagement = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-management-class");
newClassManagement.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassManagement);
return false;
});
var newClassLeadership = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-leadership-class");
newClassLeadership.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassLeadership);
return false;
});
}
function displayGymLocationContent(costMult) {
var gymStrButton = document.getElementById("location-gym-train-str");
var gymDefButton = document.getElementById("location-gym-train-def");
var gymDexButton = document.getElementById("location-gym-train-dex");
var gymAgiButton = document.getElementById("location-gym-train-agi");
gymStrButton.style.display = "block";
gymDefButton.style.display = "block";
gymDexButton.style.display = "block";
gymAgiButton.style.display = "block";
//Costs (per second)
var cost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassGymBaseCost * costMult;
//Update button text to show cost
gymStrButton.innerHTML = "Train Strength ($" + cost + " / sec)";
gymDefButton.innerHTML = "Train Defense ($" + cost + " / sec)";
gymDexButton.innerHTML = "Train Dexterity ($" + cost + " / sec)";
gymAgiButton.innerHTML = "Train Agility ($" + cost + " / sec)";
}
function setGymLocationButtons(costMult, expMult) {
var gymStr = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-gym-train-str");
gymStr.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassGymStrength);
return false;
});
var gymDef = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-gym-train-def");
gymDef.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassGymDefense);
return false;
});
var gymDex = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-gym-train-dex");
gymDex.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity);
return false;
});
var gymAgi = Object(__WEBPACK_IMPORTED_MODULE_10__utils_HelperFunctions_js__["b" /* clearEventListeners */])("location-gym-train-agi");
gymAgi.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ClassGymAgility);
return false;
});
}
function setInfiltrateButton(btn, companyName, startLevel, val, maxClearance, difficulty) {
btn.style.display = "block";
btn.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].loadInfiltrationContent();
Object(__WEBPACK_IMPORTED_MODULE_4__Infiltration_js__["a" /* beginInfiltration */])(companyName, startLevel, val, maxClearance, difficulty)
return false;
});
}
//Finds the next target job for the player at the given company (loc) and
//adds the tooltiptext to the Application button, given by 'button'
function setJobRequirementTooltip(loc, entryPosType, btn) {
var company = __WEBPACK_IMPORTED_MODULE_0__Company_js__["a" /* Companies */][loc];
if (company == null) {return;}
var pos = __WEBPACK_IMPORTED_MODULE_5__Player_js__["a" /* Player */].getNextCompanyPosition(company, entryPosType);
if (pos == null) {return};
if (!company.hasPosition(pos)) {return;}
var reqText = Object(__WEBPACK_IMPORTED_MODULE_0__Company_js__["f" /* getJobRequirementText */])(company, pos, true);
btn.innerHTML += "<span class='tooltiptext'>" + reqText + "</span>";
}
function travelBoxCreate(destCityName, cost) {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
yesBtn.innerHTML = "Yes";
noBtn.innerHTML = "No";
noBtn.addEventListener("click", () => {
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
return false;
});
yesBtn.addEventListener("click", () => {
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
travelToCity(destCityName, cost);
return false;
});
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("Would you like to travel to " + destCityName + "? The trip will cost $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2) + ".");
}
function purchaseServerBoxCreate(ram, cost) {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])();
var noBtn = Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])();
yesBtn.innerHTML = "Purchase Server";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_7__ServerPurchases_js__["b" /* purchaseServer */])(ram, cost);
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])();
});
noBtn.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])();
});
Object(__WEBPACK_IMPORTED_MODULE_13__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Would you like to purchase a new server with " + ram +
"GB of RAM for $" + Object(__WEBPACK_IMPORTED_MODULE_12__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2) + "?<br><br>" +
"Please enter the server hostname below:<br>");
}
/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Settings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return initSettings; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return setSettingsLabels; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadSettings; });
/* Settings.js */
let Settings = {
CodeInstructionRunTime: 100,
MaxLogCapacity: 50,
MaxPortCapacity: 50,
SuppressMessages: false,
SuppressFactionInvites: false,
}
function loadSettings(saveString) {
Settings = JSON.parse(saveString);
}
function initSettings() {
Settings.CodeInstructionRunTime = 100;
Settings.MaxLogCapacity = 50;
Settings.MaxPortCapacity = 50;
Settings.SuppressMessages = false;
Settings.SuppressFactionInvites = 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")
//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;
//Set handlers for when input changes
document.getElementById("settingsNSExecTimeRangeVal").oninput = function() {
nsExecTime.innerHTML = this.value + 'ms';
Settings.CodeInstructionRunTime = this.value;
};
document.getElementById("settingsNSLogRangeVal").oninput = function() {
nsLogLimit.innerHTML = this.value;
Settings.MaxLogCapacity = this.value;
};
document.getElementById("settingsNSPortRangeVal").oninput = function() {
nsPortLimit.innerHTML = this.value;
Settings.MaxPortCapacity = this.value;
};
document.getElementById("settingsSuppressMessages").onclick = function() {
Settings.SuppressMessages = this.checked;
};
document.getElementById("settingsSuppressFactionInvites").onclick = function() {
Settings.SuppressFactionInvites = this.checked;
};
}
/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Programs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return displayCreateProgramContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getNumAvailableCreateProgram; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initCreateProgramButtons; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0);
/* Create programs */
let Programs = {
NukeProgram: "NUKE.exe",
BruteSSHProgram: "BruteSSH.exe",
FTPCrackProgram: "FTPCrack.exe",
RelaySMTPProgram: "relaySMTP.exe",
HTTPWormProgram: "HTTPWorm.exe",
SQLInjectProgram: "SQLInject.exe",
DeepscanV1: "DeepscanV1.exe",
DeepscanV2: "DeepscanV2.exe",
ServerProfiler: "ServerProfiler.exe",
AutoLink: "AutoLink.exe",
Flight: "fl1ght.exe",
};
//TODO Right now the times needed to complete work are hard-coded...
//maybe later make this dependent on hacking level or something
function displayCreateProgramContent() {
var nukeALink = document.getElementById("create-program-nuke");
var bruteSshALink = document.getElementById("create-program-brutessh");
var ftpCrackALink = document.getElementById("create-program-ftpcrack");
var relaySmtpALink = document.getElementById("create-program-relaysmtp");
var httpWormALink = document.getElementById("create-program-httpworm");
var sqlInjectALink = document.getElementById("create-program-sqlinject");
var deepscanv1ALink = document.getElementById("create-program-deepscanv1");
var deepscanv2ALink = document.getElementById("create-program-deepscanv2");
var servProfilerALink = document.getElementById("create-program-serverprofiler");
var autolinkALink = document.getElementById("create-program-autolink");
nukeALink.style.display = "none";
bruteSshALink.style.display = "none";
ftpCrackALink.style.display = "none";
relaySmtpALink.style.display = "none";
httpWormALink.style.display = "none";
sqlInjectALink.style.display = "none";
deepscanv1ALink.style.display = "none";
deepscanv2ALink.style.display = "none";
servProfilerALink.style.display = "none";
autolinkALink.style.display = "none";
//NUKE.exe (in case you delete it lol)
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) {
nukeALink.style.display = "inline-block";
}
//BruteSSH
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 50) {
bruteSshALink.style.display = "inline-block";
}
//FTPCrack
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 100) {
ftpCrackALink.style.display = "inline-block";
}
//relaySMTP
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 250) {
relaySmtpALink.style.display = "inline-block";
}
//HTTPWorm
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 500) {
httpWormALink.style.display = "inline-block";
}
//SQLInject
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 750) {
sqlInjectALink.style.display = "inline-block";
}
//Deepscan V1 and V2
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.DeepscanV1) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 75) {
deepscanv1ALink.style.display = "inline-block";
}
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.DeepscanV2) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 400) {
deepscanv2ALink.style.display = "inline-block";
}
//Server profiler
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.ServerProfiler) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 75) {
servProfilerALink.style.display = "inline-block";
}
//Auto Link
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.AutoLink) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 25) {
autolinkALink.style.display = "inline-block";
}
}
//Returns the number of programs that are currently available to be created
function getNumAvailableCreateProgram() {
var count = 0;
//PortHack.exe (in case you delete it lol)
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.NukeProgram) == -1) {
++count;
}
//BruteSSH
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.BruteSSHProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 50) {
++count;
}
//FTPCrack
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.FTPCrackProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 100) {
++count;
}
//relaySMTP
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.RelaySMTPProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 250) {
++count;
}
//HTTPWorm
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.HTTPWormProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 500) {
++count;
}
//SQLInject
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.indexOf(Programs.SQLInjectProgram) == -1 &&
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 750) {
++count;
}
//Deepscan V1 and V2
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.DeepscanV1) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 75) {
++count;
}
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.DeepscanV2) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 400) {
++count;
}
//Server profiler
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.ServerProfiler) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 75) {
++count;
}
//Auto link
if (!__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hasProgram(Programs.AutoLink) && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill >= 25) {
++count;
}
if (count > 0) {__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].firstProgramAvailable = true;}
return count;
}
function initCreateProgramButtons() {
var nukeALink = document.getElementById("create-program-nuke");
var bruteSshALink = document.getElementById("create-program-brutessh");
var ftpCrackALink = document.getElementById("create-program-ftpcrack");
var relaySmtpALink = document.getElementById("create-program-relaysmtp");
var httpWormALink = document.getElementById("create-program-httpworm");
var sqlInjectALink = document.getElementById("create-program-sqlinject");
var deepscanv1ALink = document.getElementById("create-program-deepscanv1");
var deepscanv2ALink = document.getElementById("create-program-deepscanv2");
var servProfilerALink = document.getElementById("create-program-serverprofiler");
var autolinkALink = document.getElementById("create-program-autolink");
nukeALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.NukeProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes, 1);
return false;
});
bruteSshALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.BruteSSHProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes * 2, 50);
return false;
});
ftpCrackALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.FTPCrackProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 100);
return false;
});
relaySmtpALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.RelaySMTPProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 250);
return false;
});
httpWormALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.HTTPWormProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPer4Hours, 500);
return false;
});
sqlInjectALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.SQLInjectProgram, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours, 750);
return false;
});
deepscanv1ALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.DeepscanV1, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 75);
return false;
});
deepscanv2ALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.DeepscanV2, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 400);
return false;
});
servProfilerALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.ServerProfiler, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 75);
return false;
});
autolinkALink.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCreateProgramWork(Programs.AutoLink, __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 25);
return false;
});
}
/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return WorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return workerScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptPorts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return runScriptsLoop; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return killWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return addWorkerScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return updateOnlineScriptTimes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return prestigeWorkerScripts; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__ = __webpack_require__(45);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__ = __webpack_require__(57);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_acorn_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(1);
function WorkerScript(runningScriptObj) {
this.name = runningScriptObj.filename;
this.running = false;
this.serverIp = null;
this.code = runningScriptObj.scriptRef.code;
this.env = new __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__["a" /* Environment */](this);
this.env.set("args", runningScriptObj.args);
this.output = "";
this.ramUsage = 0;
this.scriptRef = runningScriptObj;
this.errorMessage = "";
this.args = runningScriptObj.args;
}
//Returns the server on which the workerScript is running
WorkerScript.prototype.getServer = function() {
return __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][this.serverIp];
}
//Array containing all scripts that are running across all servers, to easily run them all
let workerScripts = [];
let NetscriptPorts = {
Port1: [],
Port2: [],
Port3: [],
Port4: [],
Port5: [],
Port6: [],
Port7: [],
Port8: [],
Port9: [],
Port10: [],
}
function prestigeWorkerScripts() {
for (var i = 0; i < workerScripts.length; ++i) {
Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]);
workerScripts[i].env.stopFlag = true;
}
workerScripts.length = 0;
}
//Loop through workerScripts and run every script that is not currently running
function runScriptsLoop() {
//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) {
try {
var ast = Object(__WEBPACK_IMPORTED_MODULE_7__utils_acorn_js__["parse"])(workerScripts[i].code);
//console.log(ast);
} catch (e) {
console.log("Error parsing script: " + workerScripts[i].name);
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Syntax ERROR in " + workerScripts[i].name + ":<br>" + e);
workerScripts[i].env.stopFlag = true;
continue;
}
workerScripts[i].running = true;
var p = Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["a" /* 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");
}, function(w) {
//console.log(w);
if (w instanceof Error) {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* 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 instanceof WorkerScript) {
if (Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script runtime error: <br>Server Ip: " + serverIp +
"<br>Script name: " + scriptName +
"<br>Args:" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["f" /* printArray */])(w.args) + "<br>" + 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(__WEBPACK_IMPORTED_MODULE_4__NetscriptEvaluator_js__["b" /* isScriptErrorMessage */])(w)) {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_8__utils_DialogBox_js__["a" /* dialogBoxCreate */])("An unknown script died for an unknown reason. This is a bug please contact game dev");
}
});
}
}
//Delete any scripts that finished or have been killed. Loop backwards bc removing
//items fucks up the indexing
for (var i = workerScripts.length - 1; i >= 0; i--) {
if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == true) {
console.log("Deleting script: " + workerScripts[i].name);
//Delete script from the runningScripts array on its host serverIp
var ip = workerScripts[i].serverIp;
var name = workerScripts[i].name;
for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.length; j++) {
if (__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].filename == name &&
Object(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts[j].args, workerScripts[i].args)) {
__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].runningScripts.splice(j, 1);
break;
}
}
//Free RAM
__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip].ramUsed -= workerScripts[i].ramUsage;
//Delete script from Active Scripts
Object(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["b" /* deleteActiveScriptsItem */])(workerScripts[i]);
//Delete script from workerScripts
workerScripts.splice(i, 1);
}
}
setTimeout(runScriptsLoop, 10000);
}
//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(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* compareArrays */])(workerScripts[i].args, runningScriptObj.args)) {
workerScripts[i].env.stopFlag = true;
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(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1);
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(__WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__["a" /* 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 * __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed) / 1000; //seconds
for (var i = 0; i < workerScripts.length; ++i) {
workerScripts[i].scriptRef.onlineRunningTime += time;
}
}
/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AugmentationNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Augmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return PlayerOwnedAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return installAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return initAugmentations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return applyAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return augmentationExists; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Augmentation; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Prestige_js__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__ = __webpack_require__(7);
//Augmentations
function Augmentation(name) {
this.name = name;
this.info = "";
this.owned = false;
//Price and reputation base requirements (can change based on faction multipliers)
this.baseRepRequirement = 0;
this.baseCost = 0;
//Level - Only applicable for some augmentations
// NeuroFlux Governor
this.level = 0;
}
Augmentation.prototype.setInfo = function(inf) {
this.info = inf;
}
Augmentation.prototype.setRequirements = function(rep, cost) {
this.baseRepRequirement = rep * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].AugmentationRepMultiplier * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].AugmentationRepCost;
this.baseCost = cost * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].AugmentationCostMultiplier * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].AugmentationMoneyCost;
}
//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 = __WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */][factionList[i]];
if (faction == null) {
console.log("ERROR: Could not find faction with this name:" + factionList[i]);
continue;
}
faction.augmentations.push(this.name);
}
}
Augmentation.prototype.addToAllFactions = function() {
for (var fac in __WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]) {
if (__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */].hasOwnProperty(fac)) {
var facObj = __WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */][fac];
if (facObj == null) {
console.log("ERROR: Invalid faction object");
continue;
}
facObj.augmentations.push(this.name);
}
}
}
Augmentation.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Augmentation", this);
}
Augmentation.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Augmentation, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* 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",
HacknetNodeCPUUpload: "Hacknet Node CPU Architecture Neural-Upload",
HacknetNodeCacheUpload: "Hacknet Node Cache Architecture Neural-Upload",
HacknetNodeNICUpload: "HacknetNode 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)"
}
function initAugmentations() {
for (var name in __WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]) {
if (__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */].hasOwnProperty(name)) {
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */][name].augmentations = [];
}
}
//Combat stat augmentations
var HemoRecirculator = new Augmentation(AugmentationNames.HemoRecirculator);
HemoRecirculator.setInfo("A heart implant that greatly increases the body's ability to effectively use and pump " +
"blood. <br><br> This augmentation increases all of the player's combat stats by 8%.")
HemoRecirculator.setRequirements(4000, 9000000);
HemoRecirculator.addToFactions(["Tetrads", "The Dark Army", "The Syndicate"]);
if (augmentationExists(AugmentationNames.HemoRecirculator)) {
delete Augmentations[AugmentationNames.HemoRecirculator];
}
AddToAugmentations(HemoRecirculator);
var Targeting1 = new Augmentation(AugmentationNames.Targeting1);
Targeting1.setRequirements(2000, 3000000);
Targeting1.setInfo("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. <br><br>" +
"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(AugmentationNames.Targeting2);
Targeting2.setRequirements(3500, 8500000);
Targeting2.setInfo("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. <br><br>This upgrade increases the player's dexterity " +
"by an additional 20%.");
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(AugmentationNames.Targeting3);
Targeting3.setRequirements(11000, 23000000);
Targeting3.setInfo("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. <br><br>This upgrade increases the player's dexterity " +
"by an additional 30%.");
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(AugmentationNames.SyntheticHeart);
SyntheticHeart.setRequirements(300000, 575000000);
SyntheticHeart.setInfo("This advanced artificial heart, created from plasteel and graphene, is capable of pumping more blood " +
"at much higher efficiencies than a normal human heart.<br><br> 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(AugmentationNames.SynfibrilMuscle);
SynfibrilMuscle.setRequirements(175000, 225000000);
SynfibrilMuscle.setInfo("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'.<br><br> This augmentation increases the player's " +
"strength and defense by 35%.");
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(AugmentationNames.CombatRib1);
CombatRib1.setRequirements(3000, 4750000);
CombatRib1.setInfo("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.<br><br>" +
"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(AugmentationNames.CombatRib2);
CombatRib2.setRequirements(7500, 13000000);
CombatRib2.setInfo("This is an upgrade to the Combat Rib I augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream.<br><br>This upgrade increases the player's strength and defense by an additional 15%.")
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(AugmentationNames.CombatRib3);
CombatRib3.setRequirements(14000, 24000000);
CombatRib3.setInfo("This is an upgrade to the Combat Rib II augmentation, and is capable of releasing even more potent combat-enhancing " +
"drugs into the bloodstream<br><br>. This upgrade increases the player's strength and defense by an additional 20%.");
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(AugmentationNames.NanofiberWeave);
NanofiberWeave.setRequirements(15000, 25000000);
NanofiberWeave.setInfo("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.<br><br>" +
"This augmentation increases the player's strength and defense by 25%.");
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(AugmentationNames.SubdermalArmor);
SubdermalArmor.setRequirements(350000, 650000000);
SubdermalArmor.setInfo("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.<br><br>" +
"This augmentation increases the player's defense by 125%.");
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(AugmentationNames.WiredReflexes);
WiredReflexes.setRequirements(500, 500000);
WiredReflexes.setInfo("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.<br><br>" +
"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(AugmentationNames.GrapheneBoneLacings);
GrapheneBoneLacings.setRequirements(450000, 850000000);
GrapheneBoneLacings.setInfo("A graphene-based material is grafted and fused into the user's bones, significantly increasing " +
"their density and tensile strength.<br><br>" +
"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(AugmentationNames.BionicSpine);
BionicSpine.setRequirements(18000, 25000000);
BionicSpine.setInfo("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.<br><br>" +
"This augmentation increases all of the player's combat stats by 16%.");
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(AugmentationNames.GrapheneBionicSpine);
GrapheneBionicSpine.setRequirements(650000, 1200000000);
GrapheneBionicSpine.setInfo("An upgrade to the Bionic Spine augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.<br><br>" +
"This augmentation increases all of the player's combat stats by 60%.");
GrapheneBionicSpine.addToFactions(["Fulcrum Secret Technologies", "ECorp"]);
if (augmentationExists(AugmentationNames.GrapheneBionicSpine)) {
delete Augmentations[AugmentationNames.GrapheneBionicSpine];
}
AddToAugmentations(GrapheneBionicSpine);
var BionicLegs = new Augmentation(AugmentationNames.BionicLegs);
BionicLegs.setRequirements(60000, 75000000);
BionicLegs.setInfo("Cybernetic legs created from plasteel and carbon fibers that completely replace the user's organic legs. <br><br>" +
"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(AugmentationNames.GrapheneBionicLegs);
GrapheneBionicLegs.setRequirements(300000, 900000000);
GrapheneBionicLegs.setInfo("An upgrade to the Bionic Legs augmentation. It fuses the implant with an advanced graphene " +
"material to make it much stronger and lighter.<br><br>" +
"This augmentation increases the player's agility by an additional 175%.");
GrapheneBionicLegs.addToFactions(["MegaCorp", "ECorp", "Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.GrapheneBionicLegs)) {
delete Augmentations[AugmentationNames.GrapheneBionicLegs];
}
AddToAugmentations(GrapheneBionicLegs);
//Labor stat augmentations
var SpeechProcessor = new Augmentation(AugmentationNames.SpeechProcessor); //Cochlear imlant?
SpeechProcessor.setRequirements(3000, 10000000);
SpeechProcessor.setInfo("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.<br><br>" +
"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(AugmentationNames.TITN41Injection);
TITN41Injection.setRequirements(10000, 38000000);
TITN41Injection.setInfo("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. <br><br>" +
"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(AugmentationNames.EnhancedSocialInteractionImplant);
EnhancedSocialInteractionImplant.setRequirements(150000, 275000000);
EnhancedSocialInteractionImplant.setInfo("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.<br><br>" +
"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(AugmentationNames.BitWire);
BitWire.setRequirements(1500, 2000000);
BitWire.setInfo("A small brain implant embedded in the cerebrum. This regulates and improves the brain's computing " +
"capabilities. <br><br> 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(AugmentationNames.ArtificialBioNeuralNetwork);
ArtificialBioNeuralNetwork.setRequirements(110000, 600000000);
ArtificialBioNeuralNetwork.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%<br>" +
"Increases the amount of money the player's gains from hacking by 15%<br>" +
"Inreases 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(AugmentationNames.ArtificialSynapticPotentiation);
ArtificialSynapticPotentiation.setRequirements(2500, 16000000);
ArtificialSynapticPotentiation.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 2% <br> " +
"Increases the player's hacking chance by 5%<br>" +
"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(AugmentationNames.EnhancedMyelinSheathing);
EnhancedMyelinSheathing.setRequirements(40000, 275000000);
EnhancedMyelinSheathing.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%<br>" +
"Increases the player's hacking skill by 8%<br>" +
"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(AugmentationNames.SynapticEnhancement);
SynapticEnhancement.setRequirements(800, 1500000);
SynapticEnhancement.setInfo("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.<br><br>" +
"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(AugmentationNames.NeuralRetentionEnhancement);
NeuralRetentionEnhancement.setRequirements(8000, 50000000);
NeuralRetentionEnhancement.setInfo("Chemical injections are used to permanently alter and strengthen the brain's neuronal " +
"circuits, strengthening its ability to retain information.<br><br>" +
"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(AugmentationNames.DataJack);
DataJack.setRequirements(45000, 90000000);
DataJack.setInfo("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.<br><br>" +
"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(AugmentationNames.ENM);
ENM.setRequirements(6000, 50000000);
ENM.setInfo("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.<br><br>" +
"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(AugmentationNames.ENMCore);
ENMCore.setRequirements(100000, 500000000);
ENMCore.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 3%<br>" +
"Increases the amount of money the player gains from hacking by 10%<br>" +
"Increases the player's chance of successfully performing a hack by 3%<br>" +
"Increases the player's hacking experience gain rate by 7%<br>" +
"Increases the player's hacking skill by 7%");
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(AugmentationNames.ENMCoreV2);
ENMCoreV2.setRequirements(400000, 900000000);
ENMCoreV2.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 5%<br>" +
"Increases the amount of money the player gains from hacking by 30%<br>" +
"Increases the player's chance of successfully performing a hack by 5%<br>" +
"Increases the player's hacking experience gain rate by 15%<br>" +
"Increases the player's hacking skill by 8%");
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(AugmentationNames.ENMCoreV3);
ENMCoreV3.setRequirements(700000, 1500000000);
ENMCoreV3.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 5%<br>" +
"Increases the amount of money the player gains from hacking by 40%<br>" +
"Increases the player's chance of successfully performing a hack by 10%<br>" +
"Increases the player's hacking experience gain rate by 25%<br>" +
"Increases the player's hacking skill by 10%");
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(AugmentationNames.ENMAnalyzeEngine);
ENMAnalyzeEngine.setRequirements(250000, 1200000000);
ENMAnalyzeEngine.setInfo("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.<br><br>" +
"This augmentation increases the player's hacking speed by 10%.");
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(AugmentationNames.ENMDMA);
ENMDMA.setRequirements(400000, 1400000000);
ENMDMA.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases the amount of money the player gains from hacking by 40%<br>" +
"Increases the player's chance of successfully performing a hack by 20%");
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(AugmentationNames.Neuralstimulator);
Neuralstimulator.setRequirements(20000, 600000000);
Neuralstimulator.setInfo("A cranial implant that intelligently stimulates certain areas of the brain " +
"in order to improve cognitive functions<br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%<br>" +
"Increases the player's chance of successfully performing a hack by 10%<br>" +
"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(AugmentationNames.NeuralAccelerator);
NeuralAccelerator.setRequirements(80000, 350000000);
NeuralAccelerator.setInfo("A microprocessor that accelerates the processing " +
"speed of biological neural networks. This is a cranial implant that is embedded inside the brain. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking skill by 10%<br>" +
"Increases the player's hacking experience gain rate by 15%<br>" +
"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(AugmentationNames.CranialSignalProcessorsG1);
CranialSignalProcessorsG1.setRequirements(4000, 14000000);
CranialSignalProcessorsG1.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 1%<br>" +
"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(AugmentationNames.CranialSignalProcessorsG2);
CranialSignalProcessorsG2.setRequirements(7500, 25000000);
CranialSignalProcessorsG2.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 2%<br>" +
"Increases the player's chance of successfully performing a hack by 5%<br>" +
"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(AugmentationNames.CranialSignalProcessorsG3);
CranialSignalProcessorsG3.setRequirements(20000, 110000000);
CranialSignalProcessorsG3.setInfo("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. <br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking speed by 2%<br>" +
"Increases the amount of money the player gains from hacking by 15%<br>" +
"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(AugmentationNames.CranialSignalProcessorsG4);
CranialSignalProcessorsG4.setRequirements(50000, 220000000);
CranialSignalProcessorsG4.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 2%<br>" +
"Increases the amount of money the player gains from hacking by 20%<br>" +
"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(AugmentationNames.CranialSignalProcessorsG5);
CranialSignalProcessorsG5.setRequirements(100000, 450000000);
CranialSignalProcessorsG5.setInfo("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. <br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 30%<br>" +
"Increases the amount of money the player gains from hacking by 25%<br>" +
"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(AugmentationNames.NeuronalDensification);
NeuronalDensification.setRequirements(75000, 275000000);
NeuronalDensification.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking skill by 15%<br>" +
"Increases the player's hacking experience gain rate by 10%<br>"+
"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(AugmentationNames.NuoptimalInjectorImplant);
NuoptimalInjectorImplant.setRequirements(2000, 4000000);
NuoptimalInjectorImplant.setInfo("This torso implant automatically injects nootropic supplements into " +
"the bloodstream to improve memory, increase focus, and provide other " +
"cognitive enhancements.<br><br>" +
"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(AugmentationNames.SpeechEnhancement);
SpeechEnhancement.setRequirements(1000, 2500000);
SpeechEnhancement.setInfo("An advanced neural implant that improves your speaking abilities, making " +
"you more convincing and likable in conversations and overall improving your " +
"social interactions.<br><br>" +
"This augmentation:<br>" +
"Increases the player's charisma by 10%<br>" +
"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(AugmentationNames.FocusWire); //Stops procrastination
FocusWire.setRequirements(30000, 180000000);
FocusWire.setInfo("A cranial implant that stops procrastination by blocking specific neural pathways " +
"in the brain.<br><br>" +
"This augmentation: <br>" +
"Increases all experience gains by 5%<br>" +
"Increases the amount of money the player gains from working by 20%<br>" +
"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(AugmentationNames.PCDNI);
PCDNI.setRequirements(150000, 750000000);
PCDNI.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 30%<br>" +
"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(AugmentationNames.PCDNIOptimizer);
PCDNIOptimizer.setRequirements(200000, 900000000);
PCDNIOptimizer.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 75%<br>" +
"Increases the player's hacking skill by 10%");
PCDNIOptimizer.addToFactions(["Fulcrum Secret Technologies", "ECorp", "Blade Industries"]);
if (augmentationExists(AugmentationNames.PCDNIOptimizer)) {
delete Augmentations[AugmentationNames.PCDNIOptimizer];
}
AddToAugmentations(PCDNIOptimizer);
var PCDNINeuralNetwork = new Augmentation(AugmentationNames.PCDNINeuralNetwork);
PCDNINeuralNetwork.setRequirements(600000, 1500000000);
PCDNINeuralNetwork.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of reputation the player gains when working for a company by 100%<br>" +
"Increases the player's hacking skill by 10%<br>" +
"Increases the player's hacking speed by 5%");
PCDNINeuralNetwork.addToFactions(["Fulcrum Secret Technologies"]);
if (augmentationExists(AugmentationNames.PCDNINeuralNetwork)) {
delete Augmentations[AugmentationNames.PCDNINeuralNetwork];
}
AddToAugmentations(PCDNINeuralNetwork);
var ADRPheromone1 = new Augmentation(AugmentationNames.ADRPheromone1);
ADRPheromone1.setRequirements(1500, 3500000);
ADRPheromone1.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the amount of reputation the player gains when working for a company by 10% <br>" +
"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);
//HacknetNode Augmentations
var HacknetNodeCPUUpload = new Augmentation(AugmentationNames.HacknetNodeCPUUpload);
HacknetNodeCPUUpload.setRequirements(1500, 2200000);
HacknetNodeCPUUpload.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money produced by Hacknet Nodes by 15%<br>" +
"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(AugmentationNames.HacknetNodeCacheUpload);
HacknetNodeCacheUpload.setRequirements(1000, 1100000);
HacknetNodeCacheUpload.setInfo("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.<br><br>" +
"This augmentation:<br> " +
"Increases the amount of money produced by Hacknet Nodes by 10%<br>" +
"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(AugmentationNames.HacknetNodeNICUpload);
HacknetNodeNICUpload.setRequirements(750, 900000);
HacknetNodeNICUpload.setInfo("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.<br><br>" +
"This augmentation:<br>" +
"Increases the amount of money produced by Hacknet Nodes by 10%<br>" +
"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(AugmentationNames.HacknetNodeKernelDNI);
HacknetNodeKernelDNI.setRequirements(3000, 8000000);
HacknetNodeKernelDNI.setInfo("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.<br><br>" +
"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(AugmentationNames.HacknetNodeCoreDNI);
HacknetNodeCoreDNI.setRequirements(5000, 12000000);
HacknetNodeCoreDNI.setInfo("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.<br><br>" +
"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(AugmentationNames.NeuroFluxGovernor);
if (augmentationExists(AugmentationNames.NeuroFluxGovernor)) {
var nextLevel = Object(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["e" /* getNextNeurofluxLevel */])();
NeuroFluxGovernor.level = nextLevel - 1;
mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].NeuroFluxGovernorLevelMult, NeuroFluxGovernor.level);
NeuroFluxGovernor.setRequirements(500 * mult, 750000 * mult);
delete Augmentations[AugmentationNames.NeuroFluxGovernor];
} else {
var nextLevel = Object(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["e" /* getNextNeurofluxLevel */])();
NeuroFluxGovernor.level = nextLevel - 1;
mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].NeuroFluxGovernorLevelMult, NeuroFluxGovernor.level);
NeuroFluxGovernor.setRequirements(500 * mult, 750000 * mult);
}
NeuroFluxGovernor.setInfo("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. <br><br> " +
"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%");
NeuroFluxGovernor.addToAllFactions();
AddToAugmentations(NeuroFluxGovernor);
var Neurotrainer1 = new Augmentation(AugmentationNames.Neurotrainer1);
Neurotrainer1.setRequirements(400, 800000);
Neurotrainer1.setInfo("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.<br><br>" +
"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(AugmentationNames.Neurotrainer2);
Neurotrainer2.setRequirements(4000, 9000000);
Neurotrainer2.setInfo("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.<br><br>" +
"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(AugmentationNames.Neurotrainer3);
Neurotrainer3.setRequirements(10000, 26000000);
Neurotrainer3.setInfo("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.<br><br>" +
"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(AugmentationNames.Hypersight);
Hypersight.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases the player's dexterity by 40%<br>" +
"Increases the player's hacking speed by 3%<br>" +
"Increases the amount of money the player gains from hacking by 10%");
Hypersight.setRequirements(60000, 550000000);
Hypersight.addToFactions(["Blade Industries", "KuaiGong International"]);
if (augmentationExists(AugmentationNames.Hypersight)) {
delete Augmentations[AugmentationNames.Hypersight];
}
AddToAugmentations(Hypersight);
var LuminCloaking1 = new Augmentation(AugmentationNames.LuminCloaking1);
LuminCloaking1.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's agility by 5% <br>" +
"Increases the amount of money the player gains from crimes by 10%");
LuminCloaking1.setRequirements(600, 1000000);
LuminCloaking1.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking1)) {
delete Augmentations[AugmentationNames.LuminCloaking1];
}
AddToAugmentations(LuminCloaking1);
var LuminCloaking2 = new Augmentation(AugmentationNames.LuminCloaking2);
LuminCloaking2.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's agility by 10% <br>" +
"Increases the player's defense by 10% <br>" +
"Increases the amount of money the player gains from crimes by 25%");
LuminCloaking2.setRequirements(2000, 6000000);
LuminCloaking2.addToFactions(["Slum Snakes", "Tetrads"]);
if (augmentationExists(AugmentationNames.LuminCloaking2)) {
delete Augmentations[AugmentationNames.LuminCloaking2];
}
AddToAugmentations(LuminCloaking2);
var SmartSonar = new Augmentation(AugmentationNames.SmartSonar);
SmartSonar.setInfo("A cochlear implant that helps the player detect and locate enemies " +
"using sound propagation. <br><br>" +
"This augmentation: <br>" +
"Increases the player's dexterity by 10%<br>" +
"Increases the player's dexterity experience gain rate by 15%<br>" +
"Increases the amount of money the player gains from crimes by 25%");
SmartSonar.setRequirements(9000, 15000000);
SmartSonar.addToFactions(["Slum Snakes"]);
if (augmentationExists(AugmentationNames.SmartSonar)) {
delete Augmentations[AugmentationNames.SmartSonar];
}
AddToAugmentations(SmartSonar);
var PowerRecirculator = new Augmentation(AugmentationNames.PowerRecirculator);
PowerRecirculator.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases all of the player's stats by 5%<br>" +
"Increases the player's experience gain rate for all stats by 10%");
PowerRecirculator.setRequirements(10000, 36000000);
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(AugmentationNames.QLink);
QLink.setInfo("A brain implant that wirelessly connects you to the Illuminati's " +
"quantum supercomputer, allowing you to access and use its incredible " +
"computing power. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking speed by 10%<br>" +
"Increases the player's chance of successfully performing a hack by 30%<br>" +
"Increases the amount of money the player gains from hacking by 100%");
QLink.setRequirements(750000, 1300000000);
QLink.addToFactions(["Illuminati"]);
if (augmentationExists(AugmentationNames.QLink)) {
delete Augmentations[AugmentationNames.QLink];
}
AddToAugmentations(QLink);
//Daedalus
var RedPill = new Augmentation(AugmentationNames.TheRedPill);
RedPill.setInfo("It's time to leave the cave");
RedPill.setRequirements(1000000, 0);
RedPill.addToFactions(["Daedalus"]);
if (augmentationExists(AugmentationNames.TheRedPill)) {
delete Augmentations[AugmentationNames.TheRedPill];
}
AddToAugmentations(RedPill);
//Covenant
var SPTN97 = new Augmentation(AugmentationNames.SPTN97);
SPTN97.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases all of the player's combat stats by 75%<br>" +
"Increases the player's hacking skill by 15%");
SPTN97.setRequirements(500000, 975000000);
SPTN97.addToFactions(["The Covenant"]);
if (augmentationExists(AugmentationNames.SPTN97)) {
delete Augmentations[AugmentationNames.SPTN97];
}
AddToAugmentations(SPTN97);
//ECorp
var HiveMind = new Augmentation(AugmentationNames.HiveMind);
HiveMind.setInfo("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.setRequirements(600000, 1100000000);
HiveMind.addToFactions(["ECorp"]);
if (augmentationExists(AugmentationNames.HiveMind)) {
delete Augmentations[AugmentationNames.HiveMind];
}
AddToAugmentations(HiveMind);
//MegaCorp
var CordiARCReactor = new Augmentation(AugmentationNames.CordiARCReactor);
CordiARCReactor.setInfo("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. <br><br>" +
"This augmentation:<br>" +
"Increases all of the player's combat stats by 35%<br>" +
"Increases all of the player's combat stat experience gain rate by 35%");
CordiARCReactor.setRequirements(450000, 1000000000);
CordiARCReactor.addToFactions(["MegaCorp"]);
if (augmentationExists(AugmentationNames.CordiARCReactor)) {
delete Augmentations[AugmentationNames.CordiARCReactor];
}
AddToAugmentations(CordiARCReactor);
//BachmanAndAssociates
var SmartJaw = new Augmentation(AugmentationNames.SmartJaw);
SmartJaw.setInfo("A bionic jaw that contains advanced hardware and software " +
"capable of psychoanalyzing and profiling the personality of " +
"others using optical imaging software. <br><br>" +
"This augmentation: <br>" +
"Increases the player's charisma by 50%. <br>" +
"Increases the player's charisma experience gain rate by 50%<br>" +
"Increases the amount of reputation the player gains for a company by 25%<br>" +
"Increases the amount of reputation the player gains for a faction by 25%");
SmartJaw.setRequirements(150000, 550000000);
SmartJaw.addToFactions(["Bachman & Associates"]);
if (augmentationExists(AugmentationNames.SmartJaw)) {
delete Augmentations[AugmentationNames.SmartJaw];
}
AddToAugmentations(SmartJaw);
//BladeIndustries
var Neotra = new Augmentation(AugmentationNames.Neotra);
Neotra.setInfo("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. <br><br>" +
"This augmentation increases the player's strength and defense by 55%");
Neotra.setRequirements(225000, 575000000);
Neotra.addToFactions(["Blade Industries"]);
if (augmentationExists(AugmentationNames.Neotra)) {
delete Augmentations[AugmentationNames.Neotra];
}
AddToAugmentations(Neotra);
//NWO
var Xanipher = new Augmentation(AugmentationNames.Xanipher);
Xanipher.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases all of the player's stats by 20%<br>" +
"Increases the player's experience gain rate for all stats by 15%");
Xanipher.setRequirements(350000, 850000000);
Xanipher.addToFactions(["NWO"]);
if (augmentationExists(AugmentationNames.Xanipher)) {
delete Augmentations[AugmentationNames.Xanipher];
}
AddToAugmentations(Xanipher);
//ClarkeIncorporated
var nextSENS = new Augmentation(AugmentationNames.nextSENS);
nextSENS.setInfo("The body is genetically re-engineered to maintain a state " +
"of negligible senescence, preventing the body from " +
"deteriorating with age. <br><br>" +
"This augmentation increases all of the player's stats by 20%");
nextSENS.setRequirements(175000, 385000000);
nextSENS.addToFactions(["Clarke Incorporated"]);
if (augmentationExists(AugmentationNames.nextSENS)) {
delete Augmentations[AugmentationNames.nextSENS];
}
AddToAugmentations(nextSENS);
//OmniTekIncorporated
var OmniTekInfoLoad = new Augmentation(AugmentationNames.OmniTekInfoLoad);
OmniTekInfoLoad.setInfo("OmniTek's data and information repository is uploaded " +
"into your brain, enhancing your programming and " +
"hacking abilities. <br><br>" +
"This augmentation:<br>" +
"Increases the player's hacking skill by 20%<br>" +
"Increases the player's hacking experience gain rate by 25%");
OmniTekInfoLoad.setRequirements(250000, 575000000)
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(AugmentationNames.PhotosyntheticCells);
PhotosyntheticCells.setInfo("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. <br><br>" +
"This augmentation increases the player's strength, defense, and agility by 40%");
PhotosyntheticCells.setRequirements(225000, 550000000);
PhotosyntheticCells.addToFactions(["KuaiGong International"]);
if (augmentationExists(AugmentationNames.PhotosyntheticCells)) {
delete Augmentations[AugmentationNames.PhotosyntheticCells];
}
AddToAugmentations(PhotosyntheticCells);
//BitRunners
var Neurolink = new Augmentation(AugmentationNames.Neurolink);
Neurolink.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's hacking skill by 15%<br>" +
"Increases the player's hacking experience gain rate by 20%<br>" +
"Increases the player's chance of successfully performing a hack by 10%<br>" +
"Increases the player's hacking speed by 5%<br>" +
"Lets the player start with the FTPCrack.exe and relaySMTP.exe programs after a reset");
Neurolink.setRequirements(350000, 875000000);
Neurolink.addToFactions(["BitRunners"]);
if (augmentationExists(AugmentationNames.Neurolink)) {
delete Augmentations[AugmentationNames.Neurolink];
}
AddToAugmentations(Neurolink);
//BlackHand
var TheBlackHand = new Augmentation(AugmentationNames.TheBlackHand);
TheBlackHand.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Increases the player's strength and dexterity by 15%<br>" +
"Increases the player's hacking skill by 10%<br>" +
"Increases the player's hacking speed by 2%<br>" +
"Increases the amount of money the player gains from hacking by 10%");
TheBlackHand.setRequirements(40000, 110000000);
TheBlackHand.addToFactions(["The Black Hand"]);
if (augmentationExists(AugmentationNames.TheBlackHand)) {
delete Augmentations[AugmentationNames.TheBlackHand];
}
AddToAugmentations(TheBlackHand);
//NiteSec
var CRTX42AA = new Augmentation(AugmentationNames.CRTX42AA);
CRTX42AA.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Improves the player's hacking skill by 8%<br>" +
"Improves the player's hacking experience gain rate by 15%");
CRTX42AA.setRequirements(18000, 45000000);
CRTX42AA.addToFactions(["NiteSec"]);
if (augmentationExists(AugmentationNames.CRTX42AA)) {
delete Augmentations[AugmentationNames.CRTX42AA];
}
AddToAugmentations(CRTX42AA);
//Chongqing
var Neuregen = new Augmentation(AugmentationNames.Neuregen);
Neuregen.setInfo("A drug that genetically modifies the neurons in the brain. " +
"The result is that these neurons never die and continuously " +
"regenerate and strengthen themselves. <br><br>" +
"This augmentation increases the player's hacking experience gain rate by 40%");
Neuregen.setRequirements(15000, 75000000);
Neuregen.addToFactions(["Chongqing"]);
if (augmentationExists(AugmentationNames.Neuregen)) {
delete Augmentations[AugmentationNames.Neuregen];
}
AddToAugmentations(Neuregen);
//Sector12
var CashRoot = new Augmentation(AugmentationNames.CashRoot);
CashRoot.setInfo("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. <br><br>" +
"This augmentation: <br>" +
"Lets the player start with $1,000,000 after a reset<br>" +
"Lets the player start with the BruteSSH.exe program after a reset");
CashRoot.setRequirements(5000, 25000000);
CashRoot.addToFactions(["Sector-12"]);
if (augmentationExists(AugmentationNames.CashRoot)) {
delete Augmentations[AugmentationNames.CashRoot];
}
AddToAugmentations(CashRoot);
//NewTokyo
var NutriGen = new Augmentation(AugmentationNames.NutriGen);
NutriGen.setInfo("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.<br><br>" +
"This augmentation: <br>" +
"Increases the player's experience gain rate for all combat stats by 20%");
NutriGen.setRequirements(2500, 500000);
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(AugmentationNames.INFRARet);
INFRARet.setInfo("A retina implant consisting of a tiny chip that sits behind the " +
"retina. This implant lets people visually detect infrared radiation. <br><br>" +
"This augmentation: <br>" +
"Increases the player's crime success rate by 25%<br>" +
"Increases the amount of money the player gains from crimes by 10%<br>" +
"Increases the player's dexterity by 10%");
INFRARet.setRequirements(3000, 6000000);
INFRARet.addToFactions(["Ishima"]);
if (augmentationExists(AugmentationNames.INFRARet)) {
delete Augmentations[AugmentationNames.INFRARet];
}
AddToAugmentations(INFRARet);
//Volhaven
var DermaForce = new Augmentation(AugmentationNames.DermaForce);
DermaForce.setInfo("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. <br><br>" +
"This augmentation increases the player's defense by 50%");
DermaForce.setRequirements(6000, 10000000);
DermaForce.addToFactions(["Volhaven"]);
if (augmentationExists(AugmentationNames.DermaForce)) {
delete Augmentations[AugmentationNames.DermaForce];
}
AddToAugmentations(DermaForce);
//SpeakersForTheDead
var GrapheneBrachiBlades = new Augmentation(AugmentationNames.GrapheneBrachiBlades);
GrapheneBrachiBlades.setInfo("An upgrade to the BrachiBlades augmentation. It infuses " +
"the retractable blades with an advanced graphene material " +
"to make them much stronger and lighter. <br><br>" +
"This augmentation:<br>" +
"Increases the player's strength and defense by 40%<br>" +
"Increases the player's crime success rate by 10%<br>" +
"Increases the amount of money the player gains from crimes by 30%");
GrapheneBrachiBlades.setRequirements(90000, 500000000);
GrapheneBrachiBlades.addToFactions(["Speakers for the Dead"]);
if (augmentationExists(AugmentationNames.GrapheneBrachiBlades)) {
delete Augmentations[AugmentationNames.GrapheneBrachiBlades];
}
AddToAugmentations(GrapheneBrachiBlades);
//DarkArmy
var GrapheneBionicArms = new Augmentation(AugmentationNames.GrapheneBionicArms);
GrapheneBionicArms.setInfo("An upgrade to the Bionic Arms augmentation. It infuses the " +
"prosthetic arms with an advanced graphene material " +
"to make them much stronger and lighter. <br><br>" +
"This augmentation increases the player's strength and dexterity by 85%");
GrapheneBionicArms.setRequirements(200000, 750000000);
GrapheneBionicArms.addToFactions(["The Dark Army"]);
if (augmentationExists(AugmentationNames.GrapheneBionicArms)) {
delete Augmentations[AugmentationNames.GrapheneBionicArms];
}
AddToAugmentations(GrapheneBionicArms);
//TheSyndicate
var BrachiBlades = new Augmentation(AugmentationNames.BrachiBlades);
BrachiBlades.setInfo("A set of retractable plasteel blades are implanted in the arm, underneath the skin. " +
"<br><br>This augmentation: <br>" +
"Increases the player's strength and defense by 15%<br>" +
"Increases the player's crime success rate by 10%<br>" +
"Increases the amount of money the player gains from crimes by 15%");
BrachiBlades.setRequirements(5000, 18000000);
BrachiBlades.addToFactions(["The Syndicate"]);
if (augmentationExists(AugmentationNames.BrachiBlades)) {
delete Augmentations[AugmentationNames.BrachiBlades];
}
AddToAugmentations(BrachiBlades);
//Tetrads
var BionicArms = new Augmentation(AugmentationNames.BionicArms);
BionicArms.setInfo("Cybernetic arms created from plasteel and carbon fibers that completely replace " +
"the user's organic arms. <br><br>" +
"This augmentation increases the user's strength and dexterity by 30%");
BionicArms.setRequirements(25000, 55000000);
BionicArms.addToFactions(["Tetrads"]);
if (augmentationExists(AugmentationNames.BionicArms)) {
delete Augmentations[AugmentationNames.BionicArms];
}
AddToAugmentations(BionicArms);
//TianDiHui
var SNA = new Augmentation(AugmentationNames.SNA);
SNA.setInfo("A cranial implant that affects the user's personality, making them better " +
"at negotiation in social situations. <br><br>" +
"This augmentation: <br>" +
"Increases the amount of money the player earns at a company by 10%<br>" +
"Increases the amount of reputation the player gains when working for a " +
"company or faction by 15%");
SNA.setRequirements(2500, 6000000);
SNA.addToFactions(["Tian Di Hui"]);
if (augmentationExists(AugmentationNames.SNA)) {
delete Augmentations[AugmentationNames.SNA];
}
AddToAugmentations(SNA);
//Update costs based on how many have been purchased
var mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultipleAugMultiplier, __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations.length);
for (var name in Augmentations) {
if (Augmentations.hasOwnProperty(name)) {
Augmentations[name].baseCost *= mult;
}
}
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].reapplyAllAugmentations();
//In BitNode-2, these crime/evil factions have all AugmentationsAvailable
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN == 2) {
console.log("Adding all augmentations to crime factions for Bit node 2");
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["Slum Snakes"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["Tetrads"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["The Syndicate"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["The Dark Army"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["Speakers for the Dead"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["NiteSec"].addAllAugmentations();
__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]["The Black Hand"].addAllAugmentations();
}
}
function applyAugmentation(aug, reapply=false) {
Augmentations[aug.name].owned = true;
switch(aug.name) {
//Combat stat augmentations
case AugmentationNames.Targeting1:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.10;
break;
case AugmentationNames.Targeting2:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.20;
break;
case AugmentationNames.Targeting3:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.30;
break;
case AugmentationNames.SyntheticHeart: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.5;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.5;
break;
case AugmentationNames.SynfibrilMuscle: //Medium-high level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.35;
break;
case AugmentationNames.CombatRib1:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.1;
break;
case AugmentationNames.CombatRib2:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.15;
break;
case AugmentationNames.CombatRib3:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.20;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.20;
break;
case AugmentationNames.NanofiberWeave: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.25;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.25;
break;
case AugmentationNames.SubdermalArmor: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 2.25;
break;
case AugmentationNames.WiredReflexes: //Low level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.05;
break;
case AugmentationNames.GrapheneBoneLacings: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.7;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.7;
break;
case AugmentationNames.BionicSpine: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.16;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.16;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.16;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.16;
break;
case AugmentationNames.GrapheneBionicSpine: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.6;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.6;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.6;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.6;
break;
case AugmentationNames.BionicLegs: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.6;
break;
case AugmentationNames.GrapheneBionicLegs: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 2.75;
break;
//Labor stats augmentations
case AugmentationNames.EnhancedSocialInteractionImplant: //Med-high level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.6;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.6;
break;
case AugmentationNames.TITN41Injection:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.SpeechProcessor: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.2;
break;
//Hacking augmentations
case AugmentationNames.BitWire:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.05;
break;
case AugmentationNames.ArtificialBioNeuralNetwork: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.12;
break;
case AugmentationNames.ArtificialSynapticPotentiation: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.05;
break;
case AugmentationNames.EnhancedMyelinSheathing: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.08;
break;
case AugmentationNames.SynapticEnhancement: //Low Level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
break;
case AugmentationNames.NeuralRetentionEnhancement: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.DataJack: //Med low level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.25;
break;
case AugmentationNames.ENM: //Medium level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCore: //Medium level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.03;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.07;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.07;
break;
case AugmentationNames.ENMCoreV2: //Medium high level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.3;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.08;
break;
case AugmentationNames.ENMCoreV3: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.25;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.1;
break;
case AugmentationNames.ENMAnalyzeEngine: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.1;
break;
case AugmentationNames.ENMDMA: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.2;
break;
case AugmentationNames.Neuralstimulator: //Medium Level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.12;
break;
case AugmentationNames.NeuralAccelerator:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.2;
break;
case AugmentationNames.CranialSignalProcessorsG1:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.05;
break;
case AugmentationNames.CranialSignalProcessorsG2:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.07;
break;
case AugmentationNames.CranialSignalProcessorsG3:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.09;
break;
case AugmentationNames.CranialSignalProcessorsG4:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_grow_mult *= 1.25;
break;
case AugmentationNames.CranialSignalProcessorsG5:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.3;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.25;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_grow_mult *= 1.75;
break;
case AugmentationNames.NeuronalDensification:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
break;
//Work augmentations
case AugmentationNames.NuoptimalInjectorImplant: //Low medium level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.2;
break;
case AugmentationNames.SpeechEnhancement: //Low level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.1;
break;
case AugmentationNames.FocusWire: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].work_money_mult *= 1.2;
break;
case AugmentationNames.PCDNI: //Med level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.3;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.08;
break;
case AugmentationNames.PCDNIOptimizer: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.75;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.1;
break;
case AugmentationNames.PCDNINeuralNetwork: //High level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.ADRPheromone1:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].faction_rep_mult *= 1.1;
break;
//Hacknet Node Augmentations
case AugmentationNames.HacknetNodeCPUUpload:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeCacheUpload:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.10;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_level_cost_mult *= 0.85;
break;
case AugmentationNames.HacknetNodeNICUpload:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= 0.9;
break;
case AugmentationNames.HacknetNodeKernelDNI:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.25;
break;
case AugmentationNames.HacknetNodeCoreDNI:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.45;
break;
//Misc augmentations
case AugmentationNames.NeuroFluxGovernor:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_grow_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].faction_rep_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_success_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_money_mult *= 1.01;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= 0.99;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult *= 0.99;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_core_cost_mult *= 0.99;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacknet_node_level_cost_mult *= 0.99;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].work_money_mult *= 1.01;
if (!reapply) {
Augmentations[aug.name].level = aug.level;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations[i].level = aug.level;
break;
}
}
}
break;
case AugmentationNames.Neurotrainer1: //Low Level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.1;
break;
case AugmentationNames.Neurotrainer2: //Medium level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.Neurotrainer3: //High Level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.2;
break;
case AugmentationNames.Hypersight: //Medium high level
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.03;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking1:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.1;
break;
case AugmentationNames.LuminCloaking2:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.25;
break;
case AugmentationNames.HemoRecirculator:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.08;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.08;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.08;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.08;
break;
case AugmentationNames.SmartSonar:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.25;
break;
case AugmentationNames.PowerRecirculator:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.05;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.1;
break;
//Unique augmentations (for factions)
case AugmentationNames.QLink:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.3;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 2;
break;
case AugmentationNames.TheRedPill:
break;
case AugmentationNames.SPTN97:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.75;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.75;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.75;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.75;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.15;
break;
case AugmentationNames.HiveMind:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_grow_mult *= 3;
break;
case AugmentationNames.CordiARCReactor:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.35;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.35;
break;
case AugmentationNames.SmartJaw:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.5;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.5;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.25;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].faction_rep_mult *= 1.25;
break;
case AugmentationNames.Neotra:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.55;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.55;
break;
case AugmentationNames.Xanipher:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_exp_mult *= 1.15;
break;
case AugmentationNames.nextSENS:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma_mult *= 1.2;
break;
case AugmentationNames.OmniTekInfoLoad:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.25;
break;
case AugmentationNames.PhotosyntheticCells:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_mult *= 1.4;
break;
case AugmentationNames.Neurolink:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.05;
break;
case AugmentationNames.TheBlackHand:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult *= 1.02;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult *= 1.1;
break;
case AugmentationNames.CRTX42AA:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_mult *= 1.08;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.15;
break;
case AugmentationNames.Neuregen:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult *= 1.4;
break;
case AugmentationNames.CashRoot:
break;
case AugmentationNames.NutriGen:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult *= 1.2;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult *= 1.2;
break;
case AugmentationNames.INFRARet:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_success_mult *= 1.25;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.1;
break;
case AugmentationNames.DermaForce:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.5;
break;
case AugmentationNames.GrapheneBrachiBlades:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.4;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_success_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.3;
break;
case AugmentationNames.GrapheneBionicArms:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.85;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.85;
break;
case AugmentationNames.BrachiBlades:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_success_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].crime_money_mult *= 1.15;
break;
case AugmentationNames.BionicArms:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_mult *= 1.3;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_mult *= 1.3;
break;
case AugmentationNames.SNA:
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].work_money_mult *= 1.1;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].company_rep_mult *= 1.15;
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].faction_rep_mult *= 1.15;
break;
default:
throw new Error("ERROR: No such augmentation!");
return;
}
if (aug.name == AugmentationNames.NeuroFluxGovernor) {
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations[i].name == AugmentationNames.NeuroFluxGovernor) {
//Already have this aug, just upgrade the level
return;
}
}
}
if (!reapply) {
var ownedAug = new PlayerOwnedAugmentation(aug.name);
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations.push(ownedAug);
}
}
function PlayerOwnedAugmentation(name) {
this.name = name;
this.level = 1;
}
function installAugmentations() {
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations.length == 0) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You have not purchased any Augmentations to install!");
return false;
}
var augmentationList = "";
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations.length; ++i) {
var aug = Augmentations[__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations[i].name];
if (aug == null) {
console.log("ERROR. Invalid augmentation");
continue;
}
applyAugmentation(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations[i]);
augmentationList += (aug.name + "<br>");
}
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].queuedAugmentations = [];
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You slowly drift to sleep as scientists put you under in order " +
"to install the following Augmentations:<br>" + augmentationList +
"<br>You wake up in your home...you feel different...");
Object(__WEBPACK_IMPORTED_MODULE_3__Prestige_js__["a" /* prestigeAugmentation */])();
}
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);
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].augmentations.push(ownedAug);
}
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].reapplyAllAugmentations();
}
/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return CompanyPositions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return initCompanies; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Companies; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getJobRequirementText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getNextCompanyPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return loadCompanies; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Company; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CompanyPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return companyExists; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__ = __webpack_require__(7);
//Netburner Company class
// Note: Company Positions can be loaded every time with init() but Company class needs
// to be saved/loaded from localStorage
function Company(name="", salaryMult=0, expMult=0, jobStatReqOffset=0) {
this.companyName = name;
this.info = "";
this.companyPositions = []; //Names (only name, not object) of all company positions
this.perks = []; //Available Perks
this.salaryMultiplier = salaryMult; //Multiplier for base salary
this.expMultiplier = expMult; //Multiplier for base exp gain
//The additional levels you need in the relevant stat to qualify for a job.
//E.g the offset for a megacorporation will be high, let's say 200, so the
//stat level you'd need to get an intern job would be 200 instead of 1.
this.jobStatReqOffset = jobStatReqOffset;
//Player-related properties for company
this.isPlayerEmployed = false;
this.playerPosition = ""; //Name (only name, not object) of the current position player holds
this.playerReputation = 1; //"Reputation" within company, gain reputation by working for company
this.favor = 0;
this.rolloverRep = 0;
};
Company.prototype.setInfo = function(inf) {
this.info = inf;
}
Company.prototype.addPosition = function(pos) {
this.companyPositions.push(pos.positionName); //Company object holds only name of positions
}
Company.prototype.addPositions = function(positions) {
for (var i = 0; i < positions.length; i++) {
this.addPosition(positions[i]);
}
}
Company.prototype.hasPosition = function(pos) {
for (var i = 0; i < this.companyPositions.length; ++i) {
if (pos.positionName == this.companyPositions[i]) {
return true;
}
}
return false;
}
Company.prototype.gainFavor = function() {
if (this.favor == null || this.favor == undefined) {this.favor = 0;}
if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;}
var res = this.getFavorGain();
if (res.length != 2) {
console.log("Error: invalid result from getFavorGain() function");
return;
}
this.favor += res[0];
this.rolloverRep = res[1];
}
Company.prototype.getFavorGain = function() {
if (this.favor == null || this.favor == undefined) {this.favor = 0;}
if (this.rolloverRep == null || this.rolloverRep == undefined) {this.rolloverRep = 0;}
var favorGain = 0, rep = this.playerReputation + this.rolloverRep;
var reqdRep = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CompanyReputationToFavorBase *
Math.pow(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CompanyReputationToFavorMult, this.favor);
while(rep > 0) {
if (rep >= reqdRep) {
++favorGain;
rep -= reqdRep;
} else {
break;
}
reqdRep *= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].FactionReputationToFavorMult;
}
return [favorGain, rep];
}
Company.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Company", this);
}
Company.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Company, value.data);
}
__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["c" /* Reviver */].constructors.Company = Company;
//Object that defines a position within a Company and its requirements
function CompanyPosition(name, reqHack, reqStr, reqDef, reqDex, reqAgi, reqCha, reqRep, salary) {
this.positionName = name;
this.requiredHacking = reqHack;
this.requiredStrength = reqStr;
this.requiredDefense = reqDef;
this.requiredDexterity = reqDex;
this.requiredAgility = reqAgi;
this.requiredCharisma = reqCha;
this.requiredReputation = reqRep;
//Base salary for a position. This will be multiplied by a company-specific multiplier. Better companies will have
//higher multipliers.
//
//NOTE: This salary denotes the $ gained every loop (200 ms)
this.baseSalary = salary;
};
//Set the parameters that are used to determine how good/effective the Player is at a job.
//The Player's "effectiveness" at a job determines how much reputation he gains when he works
//
//NOTE: These parameters should total to 100, such that each parameter represents a "weighting" of how
// important that stat/skill is for the job
CompanyPosition.prototype.setPerformanceParameters = function(hackEff, strEff, defEff, dexEff, agiEff, chaEff, posMult=1) {
if (hackEff + strEff + defEff + dexEff + agiEff + chaEff != 100) {
console.log("CompanyPosition.setPerformanceParameters() arguments do not total to 100");
return;
}
this.hackingEffectiveness = hackEff;
this.strengthEffectiveness = strEff;
this.defenseEffectiveness = defEff;
this.dexterityEffectiveness = dexEff;
this.agilityEffectiveness = agiEff;
this.charismaEffectiveness = chaEff;
this.positionMultiplier = posMult; //Reputation multiplier for this position
}
//Set the stat/skill experience a Player should gain for working at a CompanyPosition. The experience is per game loop (200 ms)
//These will be constant for a single position, but is affected by a company-specific multiplier
CompanyPosition.prototype.setExperienceGains = function(hack, str, def, dex, agi, cha) {
this.hackingExpGain = hack;
this.strengthExpGain = str;
this.defenseExpGain = def;
this.dexterityExpGain = dex;
this.agilityExpGain = agi;
this.charismaExpGain = cha;
}
//Calculate a player's effectiveness at a certain job. Returns the amount of job reputation
//that should be gained every game loop (200 ms)
CompanyPosition.prototype.calculateJobPerformance = function(hacking, str, def, dex, agi, cha) {
var hackRatio = this.hackingEffectiveness * hacking / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var strRatio = this.strengthEffectiveness * str / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var defRatio = this.defenseEffectiveness * def / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var dexRatio = this.dexterityEffectiveness * dex / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var agiRatio = this.agilityEffectiveness * agi / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var chaRatio = this.charismaEffectiveness * cha / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel;
var reputationGain = this.positionMultiplier * (hackRatio + strRatio + defRatio + dexRatio + agiRatio + chaRatio) / 100;
if (isNaN(reputationGain)) {
console.log("ERROR: Code should not reach here");
reputationGain = (hackRatio + strRatio + defRatio + dexRatio + agiRatio + chaRatio) / 100;
}
return reputationGain;
}
CompanyPosition.prototype.isSoftwareJob = function() {
if (this.positionName == "Software Engineering Intern" ||
this.positionName == "Junior Software Engineer" ||
this.positionName == "Senior Software Engineer" ||
this.positionName == "Lead Software Developer" ||
this.positionName == "Head of Software" ||
this.positionName == "Head of Engineering" ||
this.positionName == "Vice President of Technology" ||
this.positionName == "Chief Technology Officer") {
return true;
}
return false;
}
CompanyPosition.prototype.isITJob = function() {
if (this.positionName == "IT Intern" ||
this.positionName == "IT Analyst" ||
this.positionName == "IT Manager" ||
this.positionName == "Systems Administrator") {
return true;
}
return false;
}
CompanyPosition.prototype.isSecurityEngineerJob = function() {
if (this.positionName == "Security Engineer") {
return true;
}
return false;
}
CompanyPosition.prototype.isNetworkEngineerJob = function() {
if (this.positionName == "Network Engineer" || this.positionName == "Network Administrator") {
return true;
}
return false;
}
CompanyPosition.prototype.isBusinessJob = function() {
if (this.positionName == "Business Intern" ||
this.positionName == "Business Analyst" ||
this.positionName == "Business Manager" ||
this.positionName == "Operations Manager" ||
this.positionName == "Chief Financial Officer" ||
this.positionName == "Chief Executive Officer") {
return true;
}
return false;
}
CompanyPosition.prototype.isSecurityJob = function() {
if (this.positionName == "Security Guard" ||
this.positionName == "Police Officer" ||
this.positionName == "Security Officer" ||
this.positionName == "Security Supervisor" ||
this.positionName == "Head of Security") {
return true;
}
return false;
}
CompanyPosition.prototype.isAgentJob = function() {
if (this.positionName == "Field Agent" ||
this.positionName == "Secret Agent" ||
this.positionName == "Special Operative") {
return true;
}
return false;
}
CompanyPosition.prototype.isSoftwareConsultantJob = function() {
if (this.positionName == "Software Consultant" ||
this.positionName == "Senior Software Consultant") {return true;}
return false;
}
CompanyPosition.prototype.isBusinessConsultantJob = function() {
if (this.positionName == "Business Consultant" ||
this.positionName == "Senior Business Consultant") {return true;}
return false;
}
CompanyPosition.prototype.isPartTimeJob = function() {
if (this.isSoftwareConsultantJob() ||
this.isBusinessConsultantJob() ||
this.positionName == "Part-time Waiter" ||
this.positionName == "Part-time Employee") {return true;}
return false;
}
CompanyPosition.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["b" /* Generic_toJSON */])("CompanyPosition", this);
}
CompanyPosition.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(CompanyPosition, value.data);
}
__WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["c" /* Reviver */].constructors.CompanyPosition = CompanyPosition;
let CompanyPositions = {
//Constructor: CompanyPosition(name, reqHack, reqStr, reqDef, reqDex, reqAgi, reqCha, reqRep, salary)
//Software
SoftwareIntern: new CompanyPosition("Software Engineering Intern", 1, 0, 0, 0, 0, 0, 0, 30),
JuniorDev: new CompanyPosition("Junior Software Engineer", 51, 0, 0, 0, 0, 0, 8000, 72),
SeniorDev: new CompanyPosition("Senior Software Engineer", 251, 0, 0, 0, 0, 51, 40000, 150),
LeadDev: new CompanyPosition("Lead Software Developer", 401, 0, 0, 0, 0, 151, 200000, 450),
//TODO Through darkweb, maybe?
FreelanceDeveloper: new CompanyPosition("Freelance Developer", 0, 0, 0, 0, 0, 0, 0, 0),
SoftwareConsultant: new CompanyPosition("Software Consultant", 51, 0, 0, 0, 0, 0, 0, 60),
SeniorSoftwareConsultant: new CompanyPosition("Senior Software Consultant", 251, 0, 0, 0, 0, 51, 0, 120),
//IT
ITIntern: new CompanyPosition("IT Intern", 1, 0, 0, 0, 0, 0, 0, 24),
ITAnalyst: new CompanyPosition("IT Analyst", 26, 0, 0, 0, 0, 0, 7000, 60),
ITManager: new CompanyPosition("IT Manager", 151, 0, 0, 0, 0, 51, 35000, 120),
SysAdmin: new CompanyPosition("Systems Administrator", 251, 0, 0, 0, 0, 76, 175000, 375),
SecurityEngineer: new CompanyPosition("Security Engineer", 151, 0, 0, 0, 0, 26, 35000, 110),
NetworkEngineer: new CompanyPosition("Network Engineer", 151, 0, 0, 0, 0, 26, 35000, 110),
NetworkAdministrator: new CompanyPosition("Network Administrator", 251, 0, 0, 0, 0, 76, 175000, 375),
//Technology management
HeadOfSoftware: new CompanyPosition("Head of Software", 501, 0, 0, 0, 0, 251, 400000, 720),
HeadOfEngineering: new CompanyPosition("Head of Engineering", 501, 0, 0, 0, 0, 251, 800000, 1500),
VicePresident: new CompanyPosition("Vice President of Technology", 601, 0, 0, 0, 0, 401, 1600000, 2100),
CTO: new CompanyPosition("Chief Technology Officer", 751, 0, 0, 0, 0, 501, 3200000, 2400),
//Business
BusinessIntern: new CompanyPosition("Business Intern", 1, 0, 0, 0, 0, 1, 0, 42),
BusinessAnalyst: new CompanyPosition("Business Analyst", 6, 0, 0, 0, 0, 51, 8000, 90),
BusinessManager: new CompanyPosition("Business Manager", 51, 0, 0, 0, 0, 101, 40000, 180),
OperationsManager: new CompanyPosition("Operations Manager", 51, 0, 0, 0, 0, 226, 200000, 600),
CFO: new CompanyPosition("Chief Financial Officer", 76, 0, 0, 0, 0, 501, 800000, 1800),
CEO: new CompanyPosition("Chief Executive Officer", 101, 0, 0, 0, 0, 751, 3200000, 3600),
BusinessConsultant: new CompanyPosition("Business Consultant", 6, 0, 0, 0, 0, 51, 0, 80),
SeniorBusinessConsultant: new CompanyPosition("Senior Business Consultant", 51, 0, 0, 0, 0, 226, 0, 480),
//Non-tech/management jobs
PartTimeWaiter: new CompanyPosition("Part-time Waiter", 0, 0, 0, 0, 0, 0, 0, 18),
PartTimeEmployee: new CompanyPosition("Part-time Employee", 0, 0, 0, 0, 0, 0, 0, 18),
Waiter: new CompanyPosition("Waiter", 0, 0, 0, 0, 0, 0, 0, 20),
Employee: new CompanyPosition("Employee", 0, 0, 0, 0, 0, 0, 0, 20),
PoliceOfficer: new CompanyPosition("Police Officer", 11, 101, 101, 101, 101, 51, 8000, 75),
PoliceChief: new CompanyPosition("Police Chief", 101, 301, 301, 301, 301, 151, 36000, 425),
SecurityGuard: new CompanyPosition("Security Guard", 0, 51, 51, 51, 51, 1, 0, 45),
SecurityOfficer: new CompanyPosition("Security Officer", 26, 151, 151, 151, 151, 51, 8000, 175),
SecuritySupervisor: new CompanyPosition("Security Supervisor", 26, 251, 251, 251, 251, 101, 36000, 600),
HeadOfSecurity: new CompanyPosition("Head of Security", 51, 501, 501, 501, 501, 151, 144000, 1200),
FieldAgent: new CompanyPosition("Field Agent", 101, 101, 101, 101, 101, 101, 8000, 300),
SecretAgent: new CompanyPosition("Secret Agent", 201, 251, 251, 251, 251, 201, 32000, 900),
SpecialOperative: new CompanyPosition("Special Operative", 251, 501, 501, 501, 501, 251, 162000, 1800),
init: function() {
//Argument order: hack, str, def, dex, agi, cha
//Software
CompanyPositions.SoftwareIntern.setPerformanceParameters(85, 0, 0, 0, 0, 15, 0.9);
CompanyPositions.SoftwareIntern.setExperienceGains(.05, 0, 0, 0, 0, .02);
CompanyPositions.JuniorDev.setPerformanceParameters(85, 0, 0, 0, 0, 15, 1.1);
CompanyPositions.JuniorDev.setExperienceGains(.1, 0, 0, 0, 0, .05);
CompanyPositions.SeniorDev.setPerformanceParameters(80, 0, 0, 0, 0, 20, 1.3);
CompanyPositions.SeniorDev.setExperienceGains(.4, 0, 0, 0, 0, .08);
CompanyPositions.LeadDev.setPerformanceParameters(75, 0, 0, 0, 0, 25, 1.5);
CompanyPositions.LeadDev.setExperienceGains(.8, 0, 0, 0, 0, .1);
CompanyPositions.SoftwareConsultant.setPerformanceParameters(80, 0, 0, 0, 0, 20, 1);
CompanyPositions.SoftwareConsultant.setExperienceGains(.08, 0, 0, 0, 0, .03);
CompanyPositions.SeniorSoftwareConsultant.setPerformanceParameters(75, 0, 0, 0, 0, 25, 1.2);
CompanyPositions.SeniorSoftwareConsultant.setExperienceGains(.25, 0, 0, 0, 0, .06);
//Security
CompanyPositions.ITIntern.setPerformanceParameters(90, 0, 0, 0, 0, 10, 0.9);
CompanyPositions.ITIntern.setExperienceGains(.04, 0, 0, 0, 0, .01);
CompanyPositions.ITAnalyst.setPerformanceParameters(85, 0, 0, 0, 0, 15, 1.1);
CompanyPositions.ITAnalyst.setExperienceGains(.08, 0, 0, 0, 0, .02);
CompanyPositions.ITManager.setPerformanceParameters(80, 0, 0, 0, 0, 20, 1.3);
CompanyPositions.ITManager.setExperienceGains(.3, 0, 0, 0, 0, .1);
CompanyPositions.SysAdmin.setPerformanceParameters(80, 0, 0, 0, 0, 20, 1.4);
CompanyPositions.SysAdmin.setExperienceGains(.5, 0, 0, 0, 0, .05);
CompanyPositions.SecurityEngineer.setPerformanceParameters(85, 0, 0, 0, 0, 15, 1.2);
CompanyPositions.SecurityEngineer.setExperienceGains(0.4, 0, 0, 0, 0, .05);
CompanyPositions.NetworkEngineer.setPerformanceParameters(85, 0, 0, 0, 0, 15, 1.2);
CompanyPositions.NetworkEngineer.setExperienceGains(0.4, 0, 0, 0, 0, .05);
CompanyPositions.NetworkAdministrator.setPerformanceParameters(80, 0, 0, 0, 0, 20, 1.3);
CompanyPositions.NetworkAdministrator.setExperienceGains(0.5, 0, 0, 0, 0, .1);
//Technology management
CompanyPositions.HeadOfSoftware.setPerformanceParameters(75, 0, 0, 0, 0, 25, 1.6);
CompanyPositions.HeadOfSoftware.setExperienceGains(1, 0, 0, 0, 0, .5);
CompanyPositions.HeadOfEngineering.setPerformanceParameters(75, 0, 0, 0, 0, 25, 1.6);
CompanyPositions.HeadOfEngineering.setExperienceGains(1.1, 0, 0, 0, 0, .5);
CompanyPositions.VicePresident.setPerformanceParameters(70, 0, 0, 0, 0, 30, 1.75);
CompanyPositions.VicePresident.setExperienceGains(1.2, 0, 0, 0, 0, .6);
CompanyPositions.CTO.setPerformanceParameters(65, 0, 0, 0, 0, 35, 2);
CompanyPositions.CTO.setExperienceGains(1.5, 0, 0, 0, 1);
//Business
CompanyPositions.BusinessIntern.setPerformanceParameters(10, 0, 0, 0, 0, 90, 0.9);
CompanyPositions.BusinessIntern.setExperienceGains(.01, 0, 0, 0, 0, .08);
CompanyPositions.BusinessAnalyst.setPerformanceParameters(15, 0, 0, 0, 0, 85, 1.1);
CompanyPositions.BusinessAnalyst.setExperienceGains(.02, 0, 0, 0, 0, .15);
CompanyPositions.BusinessManager.setPerformanceParameters(15, 0, 0, 0, 0, 85, 1.3);
CompanyPositions.BusinessManager.setExperienceGains(.02, 0, 0, 0, 0, .3);
CompanyPositions.OperationsManager.setPerformanceParameters(15, 0, 0, 0, 0, 85, 1.5);
CompanyPositions.OperationsManager.setExperienceGains(.02, 0, 0, 0, 0, .4);
CompanyPositions.CFO.setPerformanceParameters(10, 0, 0, 0, 0, 90, 1.6);
CompanyPositions.CFO.setExperienceGains(.05, 0, 0, 0, 0, 1);
CompanyPositions.CEO.setPerformanceParameters(10, 0, 0, 0, 0, 90, 1.75);
CompanyPositions.CEO.setExperienceGains(.1, 0, 0, 0, 0, 1.5);
CompanyPositions.BusinessConsultant.setPerformanceParameters(20, 0, 0, 0, 0, 80, 1);
CompanyPositions.BusinessConsultant.setExperienceGains(.015, 0, 0, 0, 0, .15);
CompanyPositions.SeniorBusinessConsultant.setPerformanceParameters(15, 0, 0, 0, 0, 85, 1.2);
CompanyPositions.SeniorBusinessConsultant.setExperienceGains(.015, 0, 0, 0, 0, .3);
//Non-tech/management jobs
CompanyPositions.PartTimeWaiter.setPerformanceParameters(0, 10, 0, 10, 10, 70);
CompanyPositions.PartTimeWaiter.setExperienceGains(0, .0075, .0075, .0075, .0075, .04);
CompanyPositions.PartTimeEmployee.setPerformanceParameters(0, 10, 0, 10, 10, 70);
CompanyPositions.PartTimeEmployee.setExperienceGains(0, .0075, .0075, .0075, .0075, .03);
CompanyPositions.Waiter.setPerformanceParameters(0, 10, 0, 10, 10, 70);
CompanyPositions.Waiter.setExperienceGains(0, .02, .02, .02, .02, .05);
CompanyPositions.Employee.setPerformanceParameters(0, 10, 0, 10, 10, 70);
CompanyPositions.Employee.setExperienceGains(0, .02, .02, .02, .02, .04);
CompanyPositions.SecurityGuard.setPerformanceParameters(5, 20, 20, 20, 20, 15, 1);
CompanyPositions.SecurityGuard.setExperienceGains(.01, .04, .04, .04, .04, .02);
CompanyPositions.PoliceOfficer.setPerformanceParameters(5, 20, 20, 20, 20, 15, 1);
CompanyPositions.PoliceOfficer.setExperienceGains(.02, .08, .08, .08, .08, .04);
CompanyPositions.PoliceChief.setPerformanceParameters(5, 20, 20, 20, 20, 15, 1.25);
CompanyPositions.PoliceChief.setExperienceGains(.02, .1, .1, .1, .1, .1);
CompanyPositions.SecurityOfficer.setPerformanceParameters(10, 20, 20, 20, 20, 10, 1.1);
CompanyPositions.SecurityOfficer.setExperienceGains(.02, .1, .1, .1, .1, .05);
CompanyPositions.SecuritySupervisor.setPerformanceParameters(10, 15, 15, 15, 15, 30, 1.25);
CompanyPositions.SecuritySupervisor.setExperienceGains(.02, .12, .12, .12, .12, .1);
CompanyPositions.HeadOfSecurity.setPerformanceParameters(10, 15, 15, 15, 15, 30, 1.4);
CompanyPositions.HeadOfSecurity.setExperienceGains(.05, .15, .15, .15, .15, .15);
CompanyPositions.FieldAgent.setPerformanceParameters(10, 15, 15, 20, 20, 20, 1);
CompanyPositions.FieldAgent.setExperienceGains(.04, .08, .08, .08, .08, .05);
CompanyPositions.SecretAgent.setPerformanceParameters(15, 15, 15, 20, 20, 15, 1.25);
CompanyPositions.SecretAgent.setExperienceGains(.1, .15, .15, .15, .15, .1);
CompanyPositions.SpecialOperative.setPerformanceParameters(15, 15, 15, 20, 20, 15, 1.5);
CompanyPositions.SpecialOperative.setExperienceGains(.15, .2, .2, .2, .2, .15);
}
}
//Returns the next highest position in the company for the relevant career/field
//I.E returns what your next job would be if you qualify for a promotion
function getNextCompanyPosition(currPos) {
if (currPos == null) {return null;}
//Software
if (currPos.positionName == CompanyPositions.SoftwareIntern.positionName) {
return CompanyPositions.JuniorDev;
}
if (currPos.positionName == CompanyPositions.JuniorDev.positionName) {
return CompanyPositions.SeniorDev;
}
if (currPos.positionName == CompanyPositions.SeniorDev.positionName) {
return CompanyPositions.LeadDev;
}
if (currPos.positionName == CompanyPositions.LeadDev.positionName) {
return CompanyPositions.HeadOfSoftware;
}
//Software Consultant
if (currPos.positionName == CompanyPositions.SoftwareConsultant.positionName) {
return CompanyPositions.SeniorSoftwareConsultant;
}
//IT
if (currPos.positionName == CompanyPositions.ITIntern.positionName) {
return CompanyPositions.ITAnalyst;
}
if (currPos.positionName == CompanyPositions.ITAnalyst.positionName) {
return CompanyPositions.ITManager;
}
if (currPos.positionName == CompanyPositions.ITManager.positionName) {
return CompanyPositions.SysAdmin;
}
if (currPos.positionName == CompanyPositions.SysAdmin.positionName) {
return CompanyPositions.HeadOfEngineering;
}
//Security/Network Engineer
if (currPos.positionName == CompanyPositions.SecurityEngineer.positionName) {
return CompanyPositions.HeadOfEngineering;
}
if (currPos.positionName == CompanyPositions.NetworkEngineer.positionName) {
return CompanyPositions.NetworkAdministrator;
}
if (currPos.positionName == CompanyPositions.NetworkAdministrator.positionName) {
return CompanyPositions.HeadOfEngineering;
}
//Technology management
if (currPos.positionName == CompanyPositions.HeadOfSoftware.positionName) {
return CompanyPositions.HeadOfEngineering;
}
if (currPos.positionName == CompanyPositions.HeadOfEngineering.positionName) {
return CompanyPositions.VicePresident;
}
if (currPos.positionName == CompanyPositions.VicePresident.positionName) {
return CompanyPositions.CTO;
}
//Business
if (currPos.positionName == CompanyPositions.BusinessIntern.positionName) {
return CompanyPositions.BusinessAnalyst;
}
if (currPos.positionName == CompanyPositions.BusinessAnalyst.positionName) {
return CompanyPositions.BusinessManager;
}
if (currPos.positionName == CompanyPositions.BusinessManager.positionName) {
return CompanyPositions.OperationsManager;
}
if (currPos.positionName == CompanyPositions.OperationsManager.positionName) {
return CompanyPositions.CFO;
}
if (currPos.positionName == CompanyPositions.CFO.positionName) {
return CompanyPositions.CEO;
}
//Business consultant
if (currPos.positionName == CompanyPositions.BusinessConsultant.positionName) {
return CompanyPositions.SeniorBusinessConsultant;
}
//Police
if (currPos.positionName == CompanyPositions.PoliceOfficer.positionName) {
return CompanyPositions.PoliceChief;
}
//Security
if (currPos.positionName == CompanyPositions.SecurityGuard.positionName) {
return CompanyPositions.SecurityOfficer;
}
if (currPos.positionName == CompanyPositions.SecurityOfficer.positionName) {
return CompanyPositions.SecuritySupervisor;
}
if (currPos.positionName == CompanyPositions.SecuritySupervisor.positionName) {
return CompanyPositions.HeadOfSecurity;
}
//Agent
if (currPos.positionName == CompanyPositions.FieldAgent.positionName) {
return CompanyPositions.SecretAgent;
}
if (currPos.positionName == CompanyPositions.SecretAgent.positionName) {
return CompanyPositions.SpecialOperative;
}
return null;
}
/* Initialize all companies. Only called when creating new game/prestiging. Otherwise companies are
* usually loaded from localStorage */
function initCompanies() {
/* Companies that also have servers */
//Megacorporations
var ECorp = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumECorp, 3.0, 3.0, 249);
ECorp.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumECorp)) {
ECorp.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumECorp].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumECorp];
}
AddToCompanies(ECorp);
var MegaCorp = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12MegaCorp, 3.0, 3.0, 249);
MegaCorp.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12MegaCorp)) {
MegaCorp.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12MegaCorp].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12MegaCorp];
}
AddToCompanies(MegaCorp);
var BachmanAndAssociates = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumBachmanAndAssociates, 2.6, 2.6, 224);
BachmanAndAssociates.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumBachmanAndAssociates)) {
BachmanAndAssociates.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumBachmanAndAssociates].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumBachmanAndAssociates];
}
AddToCompanies(BachmanAndAssociates);
var BladeIndustries = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12BladeIndustries, 2.75, 2.75, 224);
BladeIndustries.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12BladeIndustries)) {
BladeIndustries.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12BladeIndustries].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12BladeIndustries];
}
AddToCompanies(BladeIndustries);
var NWO = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenNWO, 2.75, 2.75, 249);
NWO.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenNWO)) {
NWO.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenNWO].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenNWO];
}
AddToCompanies(NWO);
var ClarkeIncorporated = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumClarkeIncorporated, 2.25, 2.25, 224);
ClarkeIncorporated.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumClarkeIncorporated)) {
ClarkeIncorporated.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumClarkeIncorporated].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumClarkeIncorporated];
}
AddToCompanies(ClarkeIncorporated);
var OmniTekIncorporated = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated, 2.25, 2.25, 224);
OmniTekIncorporated.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated)) {
OmniTekIncorporated.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated];
}
AddToCompanies(OmniTekIncorporated);
var FourSigma = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FourSigma, 2.5, 2.5, 224);
FourSigma.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FourSigma)) {
FourSigma.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FourSigma].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FourSigma];
}
AddToCompanies(FourSigma);
var KuaiGongInternational = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational, 2.2, 2.2, 224);
KuaiGongInternational.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational)) {
KuaiGongInternational.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational];
}
AddToCompanies(KuaiGongInternational);
//Technology and communication companies ("Large" servers)
var FulcrumTechnologies = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumFulcrumTechnologies, 2.0, 2.0, 224);
FulcrumTechnologies.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumFulcrumTechnologies)) {
FulcrumTechnologies.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumFulcrumTechnologies].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumFulcrumTechnologies];
}
AddToCompanies(FulcrumTechnologies);
var StormTechnologies = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaStormTechnologies, 1.8, 1.8, 199);
StormTechnologies.addPositions([
CompanyPositions.SoftwareIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SysAdmin,
CompanyPositions.SecurityEngineer, CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.HeadOfEngineering,
CompanyPositions.VicePresident, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager, CompanyPositions.CFO,
CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaStormTechnologies)) {
StormTechnologies.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaStormTechnologies].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaStormTechnologies];
}
AddToCompanies(StormTechnologies);
var DefComm = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoDefComm, 1.75, 1.75, 199);
DefComm.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoDefComm)) {
DefComm.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoDefComm].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoDefComm];
}
AddToCompanies(DefComm);
var HeliosLabs = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenHeliosLabs, 1.8, 1.8, 199);
HeliosLabs.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenHeliosLabs)) {
HeliosLabs.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenHeliosLabs].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenHeliosLabs];
}
AddToCompanies(HeliosLabs);
var VitaLife = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoVitaLife, 1.8, 1.8, 199);
VitaLife.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst, CompanyPositions.BusinessManager,
CompanyPositions.OperationsManager, CompanyPositions.CFO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoVitaLife)) {
VitaLife.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoVitaLife].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoVitaLife];
}
AddToCompanies(VitaLife);
var IcarusMicrosystems = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems, 1.9, 1.9, 199);
IcarusMicrosystems.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst, CompanyPositions.BusinessManager,
CompanyPositions.OperationsManager, CompanyPositions.CFO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems)) {
IcarusMicrosystems.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems];
}
AddToCompanies(IcarusMicrosystems);
var UniversalEnergy = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12UniversalEnergy, 2.0, 2.0, 199);
UniversalEnergy.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst, CompanyPositions.BusinessManager,
CompanyPositions.OperationsManager, CompanyPositions.CFO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12UniversalEnergy)) {
UniversalEnergy.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12UniversalEnergy].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12UniversalEnergy];
}
AddToCompanies(UniversalEnergy);
var GalacticCybersystems = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumGalacticCybersystems, 1.9, 1.9, 199);
GalacticCybersystems.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst, CompanyPositions.BusinessManager,
CompanyPositions.OperationsManager, CompanyPositions.CFO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumGalacticCybersystems)) {
GalacticCybersystems.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumGalacticCybersystems].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumGalacticCybersystems];
}
AddToCompanies(GalacticCybersystems);
//Defense Companies ("Large" Companies)
var AeroCorp = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumAeroCorp, 1.7, 1.7, 199);
AeroCorp.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.OperationsManager, CompanyPositions.CEO,
CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer, CompanyPositions.SecuritySupervisor,
CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumAeroCorp)) {
AeroCorp.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumAeroCorp].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumAeroCorp];
}
AddToCompanies(AeroCorp);
var OmniaCybersystems = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems, 1.7, 1.7, 199);
OmniaCybersystems.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.OperationsManager, CompanyPositions.CEO,
CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer, CompanyPositions.SecuritySupervisor,
CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems)) {
OmniaCybersystems.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems];
}
AddToCompanies(OmniaCybersystems);
var SolarisSpaceSystems = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems, 1.7, 1.7, 199);
SolarisSpaceSystems.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.OperationsManager, CompanyPositions.CEO,
CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer, CompanyPositions.SecuritySupervisor,
CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems)) {
SolarisSpaceSystems.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems];
}
AddToCompanies(SolarisSpaceSystems);
var DeltaOne = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12DeltaOne, 1.6, 1.6, 199);
DeltaOne.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.CTO,
CompanyPositions.OperationsManager, CompanyPositions.CEO,
CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer, CompanyPositions.SecuritySupervisor,
CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12DeltaOne)) {
DeltaOne.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12DeltaOne].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12DeltaOne];
}
AddToCompanies(DeltaOne);
//Health, medicine, pharmaceutical companies ("Large" servers)
var GlobalPharmaceuticals = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals, 1.8, 1.8, 224);
GlobalPharmaceuticals.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager,
CompanyPositions.CFO, CompanyPositions.CEO, CompanyPositions.SecurityGuard,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals)) {
GlobalPharmaceuticals.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals];
}
AddToCompanies(GlobalPharmaceuticals);
var NovaMedical = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaNovaMedical, 1.75, 1.75, 199);
NovaMedical.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.ITIntern, CompanyPositions.BusinessIntern,
CompanyPositions.JuniorDev, CompanyPositions.SeniorDev, CompanyPositions.LeadDev,
CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITAnalyst, CompanyPositions.ITManager, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator,
CompanyPositions.HeadOfSoftware, CompanyPositions.CTO, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager,
CompanyPositions.CFO, CompanyPositions.CEO, CompanyPositions.SecurityGuard,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaNovaMedical)) {
NovaMedical.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaNovaMedical].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaNovaMedical];
}
AddToCompanies(NovaMedical);
//Other large companies
var CIA = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CIA, 2.0, 2.0, 149);
CIA.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity, CompanyPositions.FieldAgent,
CompanyPositions.SecretAgent, CompanyPositions.SpecialOperative]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CIA)) {
CIA.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CIA].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CIA];
}
AddToCompanies(CIA);
var NSA = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12NSA, 2.0, 2.0, 149);
NSA.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity, CompanyPositions.FieldAgent,
CompanyPositions.SecretAgent, CompanyPositions.SpecialOperative]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12NSA)) {
NSA.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12NSA].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12NSA];
}
AddToCompanies(NSA);
var WatchdogSecurity = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumWatchdogSecurity, 1.5, 1.5, 124);
WatchdogSecurity.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity, CompanyPositions.FieldAgent,
CompanyPositions.SecretAgent, CompanyPositions.SpecialOperative]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumWatchdogSecurity)) {
WatchdogSecurity.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumWatchdogSecurity].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumWatchdogSecurity];
}
AddToCompanies(WatchdogSecurity);
//"Medium level" companies
var LexoCorp = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenLexoCorp, 1.4, 1.4, 99);
LexoCorp.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.HeadOfSoftware, CompanyPositions.CTO,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst,
CompanyPositions.OperationsManager, CompanyPositions.CFO, CompanyPositions.CEO,
CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer, CompanyPositions.HeadOfSecurity]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenLexoCorp)) {
LexoCorp.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenLexoCorp].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenLexoCorp];
}
AddToCompanies(LexoCorp);
var RhoConstruction = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumRhoConstruction, 1.3, 1.3, 49);
RhoConstruction.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumRhoConstruction)) {
RhoConstruction.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumRhoConstruction].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumRhoConstruction];
}
AddToCompanies(RhoConstruction);
var AlphaEnterprises = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12AlphaEnterprises, 1.5, 1.5, 99);
AlphaEnterprises.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.BusinessIntern, CompanyPositions.BusinessAnalyst,
CompanyPositions.BusinessManager, CompanyPositions.OperationsManager]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12AlphaEnterprises)) {
AlphaEnterprises.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12AlphaEnterprises].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12AlphaEnterprises];
}
AddToCompanies(AlphaEnterprises);
var AevumPolice = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumPolice, 1.3, 1.3, 99);
AevumPolice.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SecurityGuard, CompanyPositions.PoliceOfficer]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumPolice)) {
AevumPolice.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumPolice].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumPolice];
}
AddToCompanies(AevumPolice);
var SysCoreSecurities = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities, 1.3, 1.3, 124);
SysCoreSecurities.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.CTO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities)) {
SysCoreSecurities.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities];
}
AddToCompanies(SysCoreSecurities);
var CompuTek = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenCompuTek, 1.2, 1.2, 74);
CompuTek.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.CTO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenCompuTek)) {
CompuTek.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenCompuTek].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].VolhavenCompuTek];
}
AddToCompanies(CompuTek);
var NetLinkTechnologies = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumNetLinkTechnologies, 1.2, 1.2, 99);
NetLinkTechnologies.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.CTO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumNetLinkTechnologies)) {
NetLinkTechnologies.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumNetLinkTechnologies].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].AevumNetLinkTechnologies];
}
AddToCompanies(NetLinkTechnologies);
var CarmichaelSecurity = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CarmichaelSecurity, 1.2, 1.2, 74);
CarmichaelSecurity.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.SysAdmin, CompanyPositions.SecurityEngineer,
CompanyPositions.NetworkEngineer, CompanyPositions.NetworkAdministrator, CompanyPositions.HeadOfSoftware,
CompanyPositions.HeadOfEngineering, CompanyPositions.SecurityGuard, CompanyPositions.SecurityOfficer,
CompanyPositions.SecuritySupervisor, CompanyPositions.HeadOfSecurity, CompanyPositions.FieldAgent,
CompanyPositions.SecretAgent, CompanyPositions.SpecialOperative]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CarmichaelSecurity)) {
CarmichaelSecurity.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CarmichaelSecurity].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12CarmichaelSecurity];
}
AddToCompanies(CarmichaelSecurity);
//"Low level" companies
var FoodNStuff = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FoodNStuff, 1, 1, 0);
FoodNStuff.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FoodNStuff)) {
FoodNStuff.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FoodNStuff].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12FoodNStuff];
}
AddToCompanies(FoodNStuff);
var JoesGuns = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12JoesGuns, 1, 1, 0);
JoesGuns.addPositions([CompanyPositions.Employee, CompanyPositions.PartTimeEmployee]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12JoesGuns)) {
JoesGuns.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12JoesGuns].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].Sector12JoesGuns];
}
AddToCompanies(JoesGuns);
var OmegaSoftware = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaOmegaSoftware, 1.1, 1.1, 49);
OmegaSoftware.addPositions([
CompanyPositions.SoftwareIntern, CompanyPositions.JuniorDev, CompanyPositions.SeniorDev,
CompanyPositions.LeadDev, CompanyPositions.SoftwareConsultant, CompanyPositions.SeniorSoftwareConsultant,
CompanyPositions.ITIntern, CompanyPositions.ITAnalyst,
CompanyPositions.ITManager, CompanyPositions.CTO, CompanyPositions.CEO]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaOmegaSoftware)) {
OmegaSoftware.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaOmegaSoftware].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].IshimaOmegaSoftware];
}
AddToCompanies(OmegaSoftware);
/* Companies that do not have servers */
var NoodleBar = new Company(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoNoodleBar, 1, 1, 0);
NoodleBar.addPositions([CompanyPositions.Waiter, CompanyPositions.PartTimeWaiter]);
if (companyExists(__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoNoodleBar)) {
NoodleBar.favor = Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoNoodleBar].favor;
delete Companies[__WEBPACK_IMPORTED_MODULE_1__Location_js__["a" /* Locations */].NewTokyoNoodleBar];
}
AddToCompanies(NoodleBar);
}
//Map of all companies that exist in the game, indexed by their name
let Companies = {}
function loadCompanies(saveString) {
Companies = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_3__utils_JSONReviver_js__["c" /* Reviver */]);
}
//Add a Company object onto the map of all Companies in the game
function AddToCompanies(company) {
var name = company.companyName;
Companies[name] = company;
}
function companyExists(name) {
return Companies.hasOwnProperty(name);
}
function getJobRequirementText(company, pos, tooltiptext=false) {
var reqText = "";
var offset = company.jobStatReqOffset;
var reqHacking = pos.requiredHacking > 0 ? pos.requiredHacking+offset : 0;
var reqStrength = pos.requiredStrength > 0 ? pos.requiredStrength+offset : 0;
var reqDefense = pos.requiredDefense > 0 ? pos.requiredDefense+offset : 0;
var reqDexterity = pos.requiredDexterity > 0 ? pos.requiredDexterity+offset : 0;
var reqAgility = pos.requiredDexterity > 0 ? pos.requiredDexterity+offset : 0;
var reqCharisma = pos.requiredCharisma > 0 ? pos.requiredCharisma+offset : 0;
var reqRep = pos.requiredReputation;
if (tooltiptext) {
reqText = "Requires:<br>";
reqText += (reqHacking.toString() + " hacking<br>");
reqText += (reqStrength.toString() + " strength<br>");
reqText += (reqDefense.toString() + " defense<br>");
reqText += (reqDexterity.toString() + " dexterity<br>");
reqText += (reqAgility.toString() + " agility<br>");
reqText += (reqCharisma.toString() + " charisma<br>");
reqText += (reqRep.toString() + " reputation");
} else {
reqText = "(Requires ";
if (reqHacking > 0) {reqText += (reqHacking + " hacking, ");}
if (reqStrength > 0) {reqText += (reqStrength + " strength, ");}
if (reqDefense > 0) {reqText += (reqDefense + " defense, ");}
if (reqDexterity > 0) {reqText += (reqDexterity + " dexterity, ");}
if (reqAgility > 0) {reqText += (reqAgility + " agility, ");}
if (reqCharisma > 0) {reqText += (reqCharisma + " charisma, ");}
if (reqRep > 1) {reqText += (reqRep + " reputation, ");}
reqText = reqText.substring(0, reqText.length - 2);
reqText += ")";
}
return reqText;
}
/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return updateScriptEditorContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return loadAllRunningScripts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return findRunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return RunningScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return Script; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllServersMap; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__ = __webpack_require__(5);
var ace = __webpack_require__(33);
__webpack_require__(35);
__webpack_require__(36);
function scriptEditorInit() {
//Initialize save and close button
var closeButton = document.getElementById("script-editor-save-and-close-button");
closeButton.addEventListener("click", function() {
saveAndCloseScriptEditor();
return false;
});
//Allow tabs (four spaces) in all textareas
var textareas = document.getElementsByTagName('textarea');
var count = textareas.length;
for(var i=0;i<count;i++){
textareas[i].onkeydown = function(e){
if(e.keyCode==9 || e.which==9){
e.preventDefault();
var start = this.selectionStart;
var end = this.selectionEnd;
//Set textarea value to: text before caret + four spaces + text after caret
let spaces = " ";
this.value = this.value.substring(0, start) + spaces + this.value.substring(end);
//Put caret at after the four spaces
this.selectionStart = this.selectionEnd = start + spaces.length;
}
}
}
};
document.addEventListener("DOMContentLoaded", scriptEditorInit, false);
//Updates line number and RAM usage in script
function updateScriptEditorContent() {
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
var codeCopy = code.repeat(1);
var ramUsage = calculateRamUsage(codeCopy);
document.getElementById("script-editor-status-text").innerText =
"RAM: " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* formatNumber */])(ramUsage, 2).toString() + "GB";
}
//Define key commands in script editor (ctrl o to save + close, etc.)
$(document).keydown(function(e) {
if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.ScriptEditor) {
//Ctrl + b
if (e.keyCode == 66 && e.ctrlKey) {
e.preventDefault();
saveAndCloseScriptEditor();
}
}
});
function saveAndCloseScriptEditor() {
var filename = document.getElementById("script-editor-filename").value;
if (__WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__["b" /* iTutorialIsRunning */] && __WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__["a" /* currITutorialStep */] == __WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalTypeScript) {
if (filename != "foodnstuff") {
Object(__WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Leave the script name as 'foodnstuff'!");
return;
}
var editor = ace.edit('javascript-editor');
var code = editor.getValue();
code = code.replace(/\s/g, "");
if (code.indexOf("while(true){hack('foodnstuff');}") == -1) {
Object(__WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Please copy and paste the code from the tutorial!");
return;
}
Object(__WEBPACK_IMPORTED_MODULE_2__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
}
if (filename == "") {
Object(__WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You must specify a filename!");
return;
}
if (checkValidFilename(filename) == false) {
Object(__WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Script filename can contain only alphanumerics, hyphens, and underscores");
return;
}
filename += ".script";
//If the current script already exists on the server, overwrite it
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].getCurrentServer().scripts.length; i++) {
if (filename == __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].getCurrentServer().scripts[i].filename) {
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].getCurrentServer().scripts[i].saveScript();
__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadTerminalContent();
return;
}
}
//If the current script does NOT exist, create a new one
var script = new Script();
script.saveScript();
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].getCurrentServer().scripts.push(script);
__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadTerminalContent();
}
//Checks that the string contains only valid characters for a filename, which are alphanumeric,
// underscores and hyphens
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
};
//Get the script data from the Script Editor and save it to the object
Script.prototype.saveScript = function() {
if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["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 + ".script";
this.filename = filename;
//Server
this.server = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].currentServer;
//Calculate/update ram usage, execution time, etc.
this.updateRamUsage();
}
}
//Updates how much RAM the script uses when it is running.
Script.prototype.updateRamUsage = function() {
var codeCopy = this.code.repeat(1);
this.ramUsage = calculateRamUsage(codeCopy);
console.log("ram usage: " + this.ramUsage);
if (isNaN(this.ramUsage)) {
Object(__WEBPACK_IMPORTED_MODULE_7__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR in calculating ram usage. This is a bug, please report to game develoepr");
}
}
function calculateRamUsage(codeCopy) {
codeCopy = codeCopy.replace(/\s/g,''); //Remove all whitespace
var baseRam = 1.4;
var whileCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "while(");
var forCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "for(");
var ifCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "if(");
var hackCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "hack(");
var growCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "grow(");
var weakenCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "weaken(");
var scanCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "scan(");
var nukeCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "nuke(");
var brutesshCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "brutessh(");
var ftpcrackCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "ftpcrack(");
var relaysmtpCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "relaysmtp(");
var httpwormCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "httpworm(");
var sqlinjectCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "sqlinject(");
var runCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "run(");
var execCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "exec(");
var killCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "kill(") + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "killall(");
var scpCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "scp(");
var hasRootAccessCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "hasRootAccess(");
var getHostnameCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getHostname(");
var getHackingLevelCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getHackingLevel(");
var getServerCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerMoneyAvailable(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerMaxMoney(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerSecurityLevel(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerBaseSecurityLevel(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerGrowth(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerRequiredHackingLevel(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerNumPortsRequired(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getServerRam(");
var fileExistsCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "fileExists(");
var isRunningCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "isRunning(");
var numOperators = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["g" /* numNetscriptOperators */])(codeCopy);
var purchaseHacknetCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "purchaseHacknetNode(");
var hacknetnodesArrayCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "hacknetnodes[");
var hnUpgLevelCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, ".upgradeLevel(");
var hnUpgRamCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, ".upgradeRam()");
var hnUpgCoreCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, ".upgradeCore()");
var scriptGetStockCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getStockPrice(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getStockPosition(");
var scriptBuySellStockCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "buyStock(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "sellStock(");
var scriptPurchaseServerCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "purchaseServer(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "deleteServer(");
var scriptRoundCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "round(");
var scriptWriteCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "write(");
var scriptReadCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "read(");
var arbScriptCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "scriptRunning(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "scriptKill(");
var getScriptCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getScriptRam(");
var getHackTimeCount = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getHackTime(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getGrowTime(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getWeakenTime(");
var singFn1Count = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "universityCourse(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "gymWorkout(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "travelToCity(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "purchaseTor(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "purchaseProgram(");
var singFn2Count = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "upgradeHomeRam(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getUpgradeHomeRamCost(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "workForCompany(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "applyToCompany(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getCompanyRep(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "checkFactionInvitations(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "joinFaction(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "workForFaction(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getFactionRep(");
var singFn3Count = Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "createProgram(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "getAugmentationCost(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "purchaseAugmentation(") +
Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["h" /* numOccurrences */])(codeCopy, "installAugmentations(");
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].bitNodeN != 4) {
singFn1Count *= 10;
singFn2Count *= 10;
singFn3Count *= 10;
}
return baseRam +
((whileCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptWhileRamCost) +
(forCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptForRamCost) +
(ifCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptIfRamCost) +
(hackCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHackRamCost) +
(growCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGrowRamCost) +
(weakenCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptWeakenRamCost) +
(scanCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptScanRamCost) +
(nukeCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptNukeRamCost) +
(brutesshCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptBrutesshRamCost) +
(ftpcrackCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptFtpcrackRamCost) +
(relaysmtpCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptRelaysmtpRamCost) +
(httpwormCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHttpwormRamCost) +
(sqlinjectCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptSqlinjectRamCost) +
(runCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptRunRamCost) +
(execCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptExecRamCost) +
(killCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptKillRamCost) +
(scpCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptScpRamCost) +
(hasRootAccessCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHasRootAccessRamCost) +
(getHostnameCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetHostnameRamCost) +
(getHackingLevelCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetHackingLevelRamCost) +
(getServerCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetServerCost) +
(fileExistsCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptFileExistsRamCost) +
(isRunningCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptIsRunningRamCost) +
(numOperators * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptOperatorRamCost) +
(purchaseHacknetCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptPurchaseHacknetRamCost) +
(hacknetnodesArrayCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHacknetNodesRamCost) +
(hnUpgLevelCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHNUpgLevelRamCost) +
(hnUpgRamCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHNUpgRamRamCost) +
(hnUpgCoreCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptHNUpgCoreRamCost) +
(scriptGetStockCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetStockRamCost) +
(scriptBuySellStockCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptBuySellStockRamCost) +
(scriptPurchaseServerCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptPurchaseServerRamCost) +
(scriptRoundCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptRoundRamCost) +
(scriptWriteCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptReadWriteRamCost) +
(scriptReadCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptReadWriteRamCost) +
(arbScriptCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptArbScriptRamCost) +
(getScriptCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetScriptRamCost) +
(getHackTimeCount * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptGetHackTimeRamCost) +
(singFn1Count * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptSingularityFn1RamCost) +
(singFn2Count * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptSingularityFn2RamCost) +
(singFn3Count * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].ScriptSingularityFn3RamCost));
}
Script.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Script", this);
}
Script.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Script, value.data);
}
__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* 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;
for (var property in __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */]) {
if (__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */].hasOwnProperty(property)) {
var server = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][property];
//Reset each server's RAM usage to 0
server.ramUsed = 0;
for (var j = 0; j < server.runningScripts.length; ++j) {
count++;
Object(__WEBPACK_IMPORTED_MODULE_3__NetscriptWorker_js__["c" /* 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 = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_5__Server_js__["j" /* processSingleServerGrowth */])(serv, timesGrown * 450);
runningScriptObj.log(serv.hostname + " grown by " + Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["c" /* 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 = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* 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;
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* 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;
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_9__utils_HelperFunctions_js__["c" /* 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
//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]);
}
RunningScript.prototype.reset = function() {
this.scriptRef.updateRamUsage();
this.offlineRunningTime = 0.01; //Seconds
this.offlineMoneyMade = 0;
this.offlineExpGained = 0;
this.onlineRunningTime = 0.01; //Seconds
this.onlineMoneyMade = 0;
this.onlineExpGained = 0;
this.logs = [];
}
RunningScript.prototype.log = function(txt) {
if (this.logs.length > __WEBPACK_IMPORTED_MODULE_6__Settings_js__["a" /* 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();
}
this.logs.push(txt);
}
RunningScript.prototype.displayLog = function() {
for (var i = 0; i < this.logs.length; ++i) {
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]);
}
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]);
}
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]);
}
this.dataMap[serverIp][3] += n;
}
RunningScript.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("RunningScript", this);
}
RunningScript.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(RunningScript, value.data);
}
__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* 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) {
for (var ip in __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */]) {
if (__WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */].hasOwnProperty(ip)) {
if (arr) {
this[ip] = [0, 0, 0, 0];
} else {
this[ip] = 0;
}
}
}
}
AllServersMap.prototype.reset = function() {
for (var ip in this) {
if (this.hasOwnProperty(ip)) {
this[ip] = 0;
}
}
}
AllServersMap.prototype.printConsole = function() {
for (var ip in this) {
if (this.hasOwnProperty(ip)) {
var serv = __WEBPACK_IMPORTED_MODULE_5__Server_js__["b" /* AllServers */][ip];
if (serv == null) {
console.log("Warning null server encountered with ip: " + ip);
continue;
}
}
}
}
AllServersMap.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["b" /* Generic_toJSON */])("AllServersMap", this);
}
AllServersMap.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(AllServersMap, value.data);
}
__WEBPACK_IMPORTED_MODULE_8__utils_JSONReviver_js__["c" /* Reviver */].constructors.AllServersMap = AllServersMap;
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return postNetburnerText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return post; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Terminal; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__DarkWeb_js__ = __webpack_require__(42);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__HelpText_js__ = __webpack_require__(56);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Literature_js__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Message_js__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__RedPill_js__ = __webpack_require__(44);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_LogBox_js__ = __webpack_require__(26);
/* Write text to terminal */
function post(input, replace=true) {
if (replace) {
$("#terminal-input").before('<tr class="posted"><td class="terminal-line" style="color: var(--my-font-color); background-color: var(--my-background-color);">' + input.replace( / /g, "&nbsp;" ) + '</td></tr>');
} else {
$("#terminal-input").before('<tr class="posted"><td class="terminal-line" style="color: var(--my-font-color); background-color: var(--my-background-color);">' + input + '</td></tr>');
}
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('<tr class="posted"><td id="hack-progress-bar" style="color: var(--my-font-color); background-color: var(--my-background-color);">' + input + '</td></tr>');
updateTerminalScroll();
}
function hackProgressPost(input) {
$("#terminal-input").before('<tr class="posted"><td id="hack-progress" style="color: var(--my-font-color); background-color: var(--my-background-color);">' + input + '</td></tr>');
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" + __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].Version);
}
//Defines key commands in terminal
$(document).keydown(function(event) {
//Terminal
if (__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].Page.Terminal) {
var terminalInput = document.getElementById("terminal-input-text-box");
if (terminalInput != null && !event.ctrlKey && !event.shiftKey) {terminalInput.focus();}
//Enter
if (event.keyCode == 13) {
event.preventDefault(); //Prevent newline from being entered in Script Editor
var command = $('input[class=terminal-input]').val();
if (command.length > 0) {
post("> " + command);
Terminal.executeCommand(command);
$('input[class=terminal-input]').val("");
}
}
//Ctrl + c when an "Action" is in progress
if (event.keyCode == 67 && event.ctrlKey && __WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"]._actionInProgress) {
post("Cancelling...");
__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"]._actionInProgress = false;
Terminal.finishAction(true);
}
//Up key to cycle through past commands
if (event.keyCode == 38) {
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);
}
//Down key
if (event.keyCode == 40) {
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;
}
}
//Tab (autocomplete)
if (event.keyCode == 9) {
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);
}
}
});
//Keep terminal in focus
let terminalCtrlPressed = false;
$(document).ready(function() {
if (__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].Page.Terminal) {
$('.terminal-input').focus();
}
});
$(document).keydown(function(e) {
if (__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].Page.Terminal) {
if (e.which == 17) {
terminalCtrlPressed = true;
} else if (terminalCtrlPressed == true) {
//Don't focus
} else {
var inputTextBox = document.getElementById("terminal-input-text-box");
if (inputTextBox != null) {
inputTextBox.focus();
}
terminalCtrlPressed = false;
}
}
})
$(document).keyup(function(e) {
if (__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].Page.Terminal) {
if (e.which == 17) {
terminalCtrlPressed = 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(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["a" /* 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].startsWith(command)) {
allPossibilities.splice(i, 1);
}
}
} else {
for (var i = allPossibilities.length-1; i >= 0; --i) {
if (!allPossibilities[i].startsWith(arg)) {
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(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["f" /* 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(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["b" /* GlobalAliases */]));
var currServ = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* 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", "free",
"hack", "help", "home", "hostname", "ifconfig", "kill", "killall",
"ls", "mem", "nano", "ps", "rm", "run", "scan", "scan-analyze",
"scp", "sudov", "tail", "theme", "top"].concat(Object.keys(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["a" /* Aliases */])).concat(Object.keys(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["b" /* GlobalAliases */]));
}
if (input.startsWith ("buy ")) {
return [__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].BruteSSHProgram, __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].FTPCrackProgram, __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram,
__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].HTTPWormProgram, __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].SQLInjectProgram, __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV1,
__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV2].concat(Object.keys(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["b" /* GlobalAliases */]));
}
if (input.startsWith("scp ") && index == 1) {
for (var iphostname in __WEBPACK_IMPORTED_MODULE_13__Server_js__["b" /* AllServers */]) {
if (__WEBPACK_IMPORTED_MODULE_13__Server_js__["b" /* AllServers */].hasOwnProperty(iphostname)) {
allPos.push(__WEBPACK_IMPORTED_MODULE_13__Server_js__["b" /* AllServers */][iphostname].ip);
allPos.push(__WEBPACK_IMPORTED_MODULE_13__Server_js__["b" /* 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 __WEBPACK_IMPORTED_MODULE_8__Message_js__["a" /* Message */])) {
allPos.push(currServ.messages[i]);
}
}
}
if (input.startsWith("connect ") || input.startsWith("telnet ")) {
//All network connections
for (var i = 0; i < currServ.serversOnNetwork.length; ++i) {
var serv = __WEBPACK_IMPORTED_MODULE_13__Server_js__["b" /* 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("nano ") ||
input.startsWith("tail ") || input.startsWith("rm ") ||
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("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 = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* 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 __WEBPACK_IMPORTED_MODULE_8__Message_js__["a" /* Message */]) {
allPos.push(currServ.messages[i].filename);
} else {
allPos.push(currServ.messages[i]);
}
}
return allPos;
}
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,
finishAction: function(cancelled = false) {
if (Terminal.hackFlag) {
Terminal.finishHack(cancelled);
} else if (Terminal.analyzeFlag) {
Terminal.finishAnalyze(cancelled);
}
},
//Complete the hack/analyze command
finishHack: function(cancelled = false) {
if (cancelled == false) {
var server = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
//Calculate whether hack was successful
var hackChance = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].calculateHackingChance();
var rand = Math.random();
console.log("Hack success chance: " + hackChance + ", rand: " + rand);
var expGainedOnSuccess = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].calculateExpGain();
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
if (__WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon] &&
__WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon] == server.ip) {
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].bitNodeN == null) {
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].bitNodeN = 1;
}
Object(__WEBPACK_IMPORTED_MODULE_11__RedPill_js__["a" /* hackWorldDaemon */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].bitNodeN);
return;
}
server.manuallyHacked = true;
var moneyGained = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].calculatePercentMoneyHacked();
moneyGained = Math.floor(server.moneyAvailable * moneyGained);
//Safety check
if (moneyGained <= 0) {moneyGained = 0;}
server.moneyAvailable -= moneyGained;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].gainMoney(moneyGained);
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].gainHackingExp(expGainedOnSuccess)
server.fortify(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].ServerFortifyAmount);
post("Hack successful! Gained $" + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(moneyGained, 2) + " and " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnSuccess, 4) + " hacking EXP");
} else { //Failure
//Player only gains 25% exp for failure? TODO Can change this later to balance
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].gainHackingExp(expGainedOnFailure)
post("Failed to hack " + server.hostname + ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnFailure, 4) + " hacking EXP");
}
}
//Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
$('input[class=terminal-input]').prop('disabled', false);
Terminal.hackFlag = false;
},
finishAnalyze: function(cancelled = false) {
if (cancelled == false) {
post(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hostname + ": ");
post("Organization name: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().organizationName);
var rootAccess = "";
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hasAdminRights) {rootAccess = "YES";}
else {rootAccess = "NO";}
post("Root Access: " + rootAccess);
post("Required hacking skill: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().requiredHackingSkill);
post("Estimated server security level(1-100): " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(Object(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["a" /* addOffset */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hackDifficulty, 5), 3));
post("Estimated chance to hack: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(Object(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["a" /* addOffset */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].calculateHackingChance() * 100, 5), 2) + "%");
post("Estimated time to hack: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(Object(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["a" /* addOffset */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].calculateHackingTime(), 5), 3) + " seconds");
post("Estimated total money available on server: $" + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(Object(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["a" /* addOffset */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().moneyAvailable, 5), 2));
post("Required number of open ports for NUKE: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().numOpenPortsRequired);
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().sshPortOpen) {
post("SSH port: Open")
} else {
post("SSH port: Closed")
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().ftpPortOpen) {
post("FTP port: Open")
} else {
post("FTP port: Closed")
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().smtpPortOpen) {
post("SMTP port: Open")
} else {
post("SMTP port: Closed")
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().httpPortOpen) {
post("HTTP port: Open")
} else {
post("HTTP port: Closed")
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().sqlPortOpen) {
post("SQL port: Open")
} else {
post("SQL port: Closed")
}
}
Terminal.analyzeFlag = false;
//Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
$('input[class=terminal-input]').prop('disabled', false);
},
executeCommand: function(command) {
command = command.trim();
//Replace all extra whitespace in command with a single space
command = command.replace(/\s\s+/g, ' ');
//Terminal history
if (Terminal.commandHistory[Terminal.commandHistory.length-1] != command) {
Terminal.commandHistory.push(command);
if (Terminal.commandHistory.length > 50) {
Terminal.commandHistory.splice(0, 1);
}
}
Terminal.commandHistoryIndex = Terminal.commandHistory.length;
//Process any aliases
command = Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["h" /* substituteAliases */])(command);
//Allow usage of ./
if (command.startsWith("./")) {
command = "run " + command.slice(2);
}
//Only split the first space
var commandArray = command.split(" ");
if (commandArray.length > 1) {
commandArray = [commandArray.shift(), commandArray.join(" ")];
}
if (commandArray.length == 0) {return;}
/****************** Interactive Tutorial Terminal Commands ******************/
if (__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["b" /* iTutorialIsRunning */]) {
var foodnstuffServ = Object(__WEBPACK_IMPORTED_MODULE_13__Server_js__["c" /* GetServerByHostname */])("foodnstuff");
if (foodnstuffServ == null) {throw new Error("Could not get foodnstuff server"); return;}
switch(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["a" /* currITutorialStep */]) {
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalHelp:
if (commandArray[0] == "help") {
post(__WEBPACK_IMPORTED_MODULE_5__HelpText_js__["b" /* TerminalHelpText */]);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalLs:
if (commandArray[0] == "ls") {
Terminal.executeListCommand(commandArray);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalScan:
if (commandArray[0] == "scan") {
Terminal.executeScanCommand(commandArray);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalScanAnalyze1:
if (commandArray.length == 1 && commandArray[0] == "scan-analyze") {
Terminal.executeScanAnalyzeCommand(1);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalScanAnalyze2:
if (commandArray.length == 2 && commandArray[0] == "scan-analyze" &&
commandArray[1] == "2") {
Terminal.executeScanAnalyzeCommand(2);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalConnect:
if (commandArray.length == 2) {
if ((commandArray[0] == "connect") &&
(commandArray[1] == "foodnstuff" || commandArray[1] == foodnstuffServ.ip)) {
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = false;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].currentServer = foodnstuffServ.ip;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = true;
post("Connected to foodnstuff");
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Wrong command! Try again!"); return;}
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalAnalyze:
if (commandArray[0] == "analyze") {
if (commandArray.length != 1) {
post("Incorrect usage of analyze command. Usage: analyze"); return;
}
//Analyze the current server for information
Terminal.analyzeFlag = true;
post("Analyzing system...");
hackProgressPost("Time left:");
hackProgressBarPost("[");
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].analyze();
//Disable terminal
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {
post("Bad command. Please follow the tutorial");
}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalNuke:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "NUKE.exe") {
foodnstuffServ.hasAdminRights = true;
post("NUKE successful! Gained root access to foodnstuff");
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalManualHack:
if (commandArray.length == 1 && commandArray[0] == "hack") {
Terminal.hackFlag = true;
hackProgressPost("Time left:");
hackProgressBarPost("[");
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hack();
//Disable terminal
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalCreateScript:
if (commandArray.length == 2 &&
commandArray[0] == "nano" && commandArray[1] == "foodnstuff.script") {
__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].loadScriptEditorContent("foodnstuff", "");
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalFree:
if (commandArray.length == 1 && commandArray[0] == "free") {
Terminal.executeFreeCommand(commandArray);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].TerminalRunScript:
if (commandArray.length == 2 &&
commandArray[0] == "run" && commandArray[1] == "foodnstuff.script") {
Terminal.runScript("foodnstuff.script");
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
case __WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["e" /* iTutorialSteps */].ActiveScriptsToTerminal:
if (commandArray.length == 2 &&
commandArray[0] == "tail" && commandArray[1] == "foodnstuff.script") {
//Check that the script exists on this machine
var runningScript = Object(__WEBPACK_IMPORTED_MODULE_12__Script_js__["d" /* findRunningScript */])("foodnstuff.script", [], __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer());
if (runningScript == null) {
post("Error: No such script exists");
return;
}
Object(__WEBPACK_IMPORTED_MODULE_17__utils_LogBox_js__["a" /* logBoxCreate */])(runningScript);
Object(__WEBPACK_IMPORTED_MODULE_6__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {post("Bad command. Please follow the tutorial");}
break;
default:
post("Please follow the tutorial, or click 'Exit Tutorial' if you'd like to skip it");
return;
}
return;
}
/****************** END INTERACTIVE TUTORIAL ******************/
/* Command parser */
var s = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
switch (commandArray[0].toLowerCase()) {
case "alias":
if (commandArray.length == 1) {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["f" /* printAliases */])();
return;
}
if (commandArray.length == 2) {
if (commandArray[1].startsWith("-g ")) {
var alias = commandArray[1].substring(3);
if (Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["e" /* parseAliasDeclaration */])(alias, true)) {
return;
}
} else {
if (Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["e" /* parseAliasDeclaration */])(commandArray[1])) {
return;
}
}
}
post('Incorrect usage of alias command. Usage: alias [-g] [aliasname="value"]');
break;
case "analyze":
if (commandArray.length != 1) {
post("Incorrect usage of analyze command. Usage: analyze"); return;
}
//Analyze the current server for information
Terminal.analyzeFlag = true;
post("Analyzing system...");
hackProgressPost("Time left:");
hackProgressBarPost("[");
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].analyze();
//Disable terminal
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
break;
case "buy":
if (__WEBPACK_IMPORTED_MODULE_14__SpecialServerIps_js__["a" /* SpecialServerIps */].hasOwnProperty("Darkweb Server")) {
Object(__WEBPACK_IMPORTED_MODULE_3__DarkWeb_js__["c" /* executeDarkwebTerminalCommand */])(commandArray);
} else {
post("You need to be connected to the Dark Web to use the buy command");
}
break;
case "cat":
if (commandArray.length != 2) {
post("Incorrect usage of cat command. Usage: cat [file]"); return;
}
var filename = commandArray[1];
//Can only edit script files
if (!filename.endsWith(".msg") && !filename.endsWith(".lit")) {
post("Error: Only .msg and .lit files are viewable with cat (filename must end with .msg or .lit)"); return;
}
for (var i = 0; i < s.messages.length; ++i) {
if (filename.endsWith(".lit") && s.messages[i] == filename) {
Object(__WEBPACK_IMPORTED_MODULE_7__Literature_js__["b" /* showLiterature */])(s.messages[i]);
return;
} else if (filename.endsWith(".msg") && s.messages[i].filename == filename) {
Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["f" /* showMessage */])(s.messages[i]);
return;
}
}
post("Error: No such file " + filename);
break;
case "check":
if (commandArray.length < 2) {
post("Incorrect number of arguments. Usage: check [script] [arg1] [arg2]...");
} else {
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
//Can only tail script files
if (scriptName.endsWith(".script") == false) {
post("Error: tail can only be called on .script files (filename must end with .script)"); return;
}
//Check that the script exists on this machine
var runningScript = Object(__WEBPACK_IMPORTED_MODULE_12__Script_js__["d" /* findRunningScript */])(scriptName, args, s);
if (runningScript == null) {
post("Error: No such script exists");
return;
}
runningScript.displayLog();
}
break;
case "clear":
case "cls":
if (commandArray.length != 1) {
post("Incorrect usage of clear/cls command. Usage: clear/cls"); return;
}
$("#terminal tr:not(:last)").remove();
postNetburnerText();
break;
case "connect":
//Disconnect from current server in terminal and connect to new one
if (commandArray.length != 2) {
post("Incorrect usage of connect command. Usage: connect [ip/hostname]");
return;
}
var ip = commandArray[1];
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().serversOnNetwork.length; i++) {
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i).ip == ip || __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i).hostname == ip) {
Terminal.connectToServer(ip);
return;
}
}
post("Host not found");
break;
case "free":
Terminal.executeFreeCommand(commandArray);
break;
case "hack":
if (commandArray.length != 1) {
post("Incorrect usage of hack command. Usage: hack"); return;
}
//Hack the current PC (usually for money)
//You can't hack your home pc or servers you purchased
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().purchasedByPlayer) {
post("Cannot hack your own machines! You are currently connected to your home PC or one of your purchased servers");
} else if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hasAdminRights == false ) {
post("You do not have admin rights for this machine! Cannot hack");
} else if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().requiredHackingSkill > __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hacking_skill) {
post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else {
Terminal.hackFlag = true;
hackProgressPost("Time left:");
hackProgressBarPost("[");
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hack();
//Disable terminal
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
}
break;
case "help":
if (commandArray.length != 1 && commandArray.length != 2) {
post("Incorrect usage of help command. Usage: help"); return;
}
if (commandArray.length == 1) {
post(__WEBPACK_IMPORTED_MODULE_5__HelpText_js__["b" /* TerminalHelpText */]);
} else {
var cmd = commandArray[1];
var txt = __WEBPACK_IMPORTED_MODULE_5__HelpText_js__["a" /* HelpTexts */][cmd];
if (txt == null) {
post("Error: No help topics match '" + cmd + "'");
return;
}
post(txt);
}
break;
case "home":
if (commandArray.length != 1) {
post("Incorrect usage of home command. Usage: home"); return;
}
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = false;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].currentServer = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getHomeComputer().ip;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = true;
post("Connected to home");
break;
case "hostname":
if (commandArray.length != 1) {
post("Incorrect usage of hostname command. Usage: hostname"); return;
}
//Print the hostname of current system
post(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hostname);
break;
case "ifconfig":
if (commandArray.length != 1) {
post("Incorrect usage of ifconfig command. Usage: ifconfig"); return;
}
//Print the IP address of the current system
post(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().ip);
break;
case "kill":
if (commandArray.length < 2) {
post("Incorrect usage of kill command. Usage: kill [scriptname] [arg1] [arg2]..."); return;
}
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
var runningScript = Object(__WEBPACK_IMPORTED_MODULE_12__Script_js__["d" /* findRunningScript */])(scriptName, args, s);
if (runningScript == null) {
post("No such script is running. Nothing to kill");
return;
}
Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__["d" /* killWorkerScript */])(runningScript, s.ip);
post("Killing " + scriptName + ". May take up to a few minutes for the scripts to die...");
break;
case "killall":
for (var i = s.runningScripts.length-1; i >= 0; --i) {
Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__["d" /* killWorkerScript */])(s.runningScripts[i], s.ip);
}
post("Killing all running scripts. May take up to a few minutes for the scripts to die...");
break;
case "ls":
Terminal.executeListCommand(commandArray);
break;
case "mem":
if (commandArray.length != 2) {
post("Incorrect usage of mem command. usage: mem [scriptname] [-t] [number threads]"); return;
}
var scriptName = commandArray[1];
var numThreads = 1;
if (scriptName.indexOf(" -t ") != -1) {
var results = scriptName.split(" ");
if (results.length != 3) {
post("Invalid use of run command. Usage: mem [script] [-t] [number threads]");
return;
}
numThreads = Math.round(Number(results[2]));
if (isNaN(numThreads) || numThreads < 1) {
post("Invalid number of threads specified. Number of threads must be greater than 1");
return;
}
scriptName = results[0];
}
var currServ = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
for (var i = 0; i < currServ.scripts.length; ++i) {
if (scriptName == currServ.scripts[i].filename) {
var scriptBaseRamUsage = currServ.scripts[i].ramUsage;
var ramUsage = scriptBaseRamUsage * numThreads * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, numThreads-1);
post("This script requires " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(ramUsage, 2) + "GB of RAM to run for " + numThreads + " thread(s)");
return;
}
}
post("ERR: No such script exists!");
break;
case "nano":
if (commandArray.length != 2) {
post("Incorrect usage of nano command. Usage: nano [scriptname]"); return;
}
var filename = commandArray[1];
//Can only edit script files
if (filename.endsWith(".script") == false) {
post("Error: Only .script files are editable with nano (filename must end with .script)"); return;
}
//Script name is the filename without the .script at the end
var scriptname = filename.substr(0, filename.indexOf(".script"));
//Check if the script already exists
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().scripts.length; i++) {
if (filename == __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().scripts[i].filename) {
__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].loadScriptEditorContent(scriptname, __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().scripts[i].code);
return;
}
}
__WEBPACK_IMPORTED_MODULE_4__engine_js__["Engine"].loadScriptEditorContent(scriptname, "");
break;
case "ps":
if (commandArray.length != 1) {
post("Incorrect usage of ps command. Usage: ps"); return;
}
for (var i = 0; i < s.runningScripts.length; i++) {
var rsObj = s.runningScripts[i];
var res = rsObj.filename;
for (var j = 0; j < rsObj.args.length; ++j) {
res += (" " + rsObj.args[j].toString());
}
post(res);
}
break;
case "rm":
if (commandArray.length != 2) {
post("Incorrect number of arguments. Usage: rm [program/script]"); return;
}
//Check programs
var delTarget = commandArray[1];
for (var i = 0; i < s.programs.length; ++i) {
if (s.programs[i] == delTarget) {
s.programs.splice(i, 1);
return;
}
}
//Check scripts
for (var i = 0; i < s.scripts.length; ++i) {
if (s.scripts[i].filename == delTarget) {
//Check that the script isnt currently running
for (var j = 0; j < s.runningScripts.length; ++j) {
if (s.runningScripts[j].filename == delTarget) {
post("Cannot delete a script that is currently running!");
return;
}
}
s.scripts.splice(i, 1);
return;
}
}
post("No such file exists");
break;
case "run":
//Run a program or a script
if (commandArray.length != 2) {
post("Incorrect number of arguments. Usage: run [program/script] [-t] [num threads] [arg1] [arg2]...");
} else {
var executableName = commandArray[1];
//Check if its a script or just a program/executable
if (executableName.indexOf(".script") == -1) {
//Not a script
Terminal.runProgram(executableName);
} else {
//Script
Terminal.runScript(executableName);
}
}
break;
case "scan":
Terminal.executeScanCommand(commandArray);
break;
case "scan-analyze":
if (commandArray.length == 1) {
Terminal.executeScanAnalyzeCommand(1);
} else if (commandArray.length == 2) {
var depth = Number(commandArray[1]);
if (isNaN(depth) || depth < 0) {
post("Incorrect usage of scan-analyze command. depth argument must be positive numeric");
return;
}
if (depth > 3 && !__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV1) &&
!__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV2)) {
post("You cannot scan-analyze with that high of a depth. Maximum depth is 3");
return;
} else if (depth > 5 && !__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV2)) {
post("You cannot scan-analyze with that high of a depth. Maximum depth is 5");
return;
} else if (depth > 10) {
post("You cannot scan-analyze with that high of a depth. Maximum depth is 10");
return;
}
Terminal.executeScanAnalyzeCommand(depth);
} else {
post("Incorrect usage of scan-analyze command. usage: scan-analyze [depth]");
}
break;
case "scp":
if (commandArray.length != 2) {
post("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
var args = commandArray[1].split(" ");
if (args.length != 2) {
post("Incorrect usage of scp command. Usage: scp [file] [destination hostname/ip]");
return;
}
var scriptname = args[0];
if (!scriptname.endsWith(".lit") && !scriptname.endsWith(".script")){
post("Error: scp only works for .script and .lit files");
return;
}
var server = Object(__WEBPACK_IMPORTED_MODULE_13__Server_js__["e" /* getServer */])(args[1]);
if (server == null) {
post("Invalid destination. " + args[1] + " not found");
return;
}
var ip = server.ip;
var currServ = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
//Scp for lit files
if (scriptname.endsWith(".lit")) {
var found = false;
var curr
for (var i = 0; i < currServ.messages.length; ++i) {
if (!(currServ.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_8__Message_js__["a" /* Message */]) && currServ.messages[i] == scriptname) {
found = true;
}
}
if (!found) {
post("Error: no such file exists!");
return;
}
for (var i = 0; i < server.messages.length; ++i) {
if (server.messages[i] === scriptname) {
post(scriptname + " copied over to " + server.hostname);
return; //Already exists
}
}
server.messages.push(scriptname);
post(scriptname + " copied over to " + server.hostname);
return;
}
//Get the current script
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) {
post("ERROR: scp() failed. No such script exists");
return;
}
//Overwrite script if it exists
for (var i = 0; i < server.scripts.length; ++i) {
if (scriptname == server.scripts[i].filename) {
post("WARNING: " + scriptname + " already exists on " + server.hostname + " and will be overwritten");
var oldScript = server.scripts[i];
oldScript.code = sourceScript.code;
oldScript.ramUsage = sourceScript.ramUsage;
post(scriptname + " overwriten on " + server.hostname);
return;
}
}
var newScript = new __WEBPACK_IMPORTED_MODULE_12__Script_js__["c" /* Script */]();
newScript.filename = scriptname;
newScript.code = sourceScript.code;
newScript.ramUsage = sourceScript.ramUsage;
newScript.server = ip;
server.scripts.push(newScript);
post(scriptname + " copied over to " + server.hostname);
break;
case "sudov":
if (commandArray.length != 1) {
post("Incorrect number of arguments. Usage: sudov"); return;
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hasAdminRights) {
post("You have ROOT access to this machine");
} else {
post("You do NOT have root access to this machine");
}
break;
case "tail":
if (commandArray.length < 2) {
post("Incorrect number of arguments. Usage: tail [script] [arg1] [arg2]...");
} else {
var results = commandArray[1].split(" ");
var scriptName = results[0];
var args = [];
for (var i = 1; i < results.length; ++i) {
args.push(results[i]);
}
//Can only tail script files
if (scriptName.endsWith(".script") == false) {
post("Error: tail can only be called on .script files (filename must end with .script)"); return;
}
//Check that the script exists on this machine
var runningScript = Object(__WEBPACK_IMPORTED_MODULE_12__Script_js__["d" /* findRunningScript */])(scriptName, args, s);
if (runningScript == null) {
post("Error: No such script exists");
return;
}
Object(__WEBPACK_IMPORTED_MODULE_17__utils_LogBox_js__["a" /* logBoxCreate */])(runningScript);
}
break;
case "theme":
//todo support theme saving
var args = commandArray[1] ? commandArray[1].split(" ") : [];
if(args.length != 1 && args.length != 3) {
post("Incorrect number of arguments.");
post("Usage: theme [default|muted|solarized] | #[background color hex] #[text color hex] #[highlight color hex]");
}else if(args.length == 1){
var themeName = args[0];
if(themeName == "default"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#000000");
}else if(themeName == "muted"){
document.body.style.setProperty('--my-highlight-color',"#ffffff");
document.body.style.setProperty('--my-font-color',"#66ff33");
document.body.style.setProperty('--my-background-color',"#252527");
}else if(themeName == "solarized"){
document.body.style.setProperty('--my-highlight-color',"#6c71c4");
document.body.style.setProperty('--my-font-color',"#839496");
document.body.style.setProperty('--my-background-color',"#002b36");
}else{
post("Theme not found");
}
}else{
inputBackgroundHex = args[0];
inputTextHex = args[1];
inputHighlightHex = args[2];
if(/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputBackgroundHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputTextHex) &&
/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(inputHighlightHex)){
document.body.style.setProperty('--my-highlight-color',inputHighlightHex);
document.body.style.setProperty('--my-font-color',inputTextHex);
document.body.style.setProperty('--my-background-color',inputBackgroundHex);
}else{
post("Invalid Hex Input for theme");
}
}
break;
case "top":
if(commandArray.length != 1) {
post("Incorrect usage of top command. Usage: top"); return;
}
post("Script Threads RAM Usage");
var currRunningScripts = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().runningScripts;
//Iterate through scripts on current server
for(var i = 0; i < currRunningScripts.length; i++) {
var script = currRunningScripts[i];
//Calculate name padding
var numSpacesScript = 32 - script.filename.length; //26 -> width of name column
if (numSpacesScript < 0) {numSpacesScript = 0;}
var spacesScript = Array(numSpacesScript+1).join(" ");
//Calculate thread padding
var numSpacesThread = 16 - (script.threads + "").length; //16 -> width of thread column
var spacesThread = Array(numSpacesThread+1).join(" ");
//Calculate and transform RAM usage
ramUsage = Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(script.scriptRef.ramUsage * script.threads, 2).toString() + "GB";
var entry = [script.filename, spacesScript, script.threads, spacesThread, ramUsage];
post(entry.join(""));
}
break;
case "unalias":
if (commandArray.length != 2) {
post('Incorrect usage of unalias name. Usage: unalias "[alias]"');
return;
} else if (!(commandArray[1].startsWith('"') && commandArray[1].endsWith('"'))) {
post('Incorrect usage of unalias name. Usage: unalias "[alias]"');
} else {
var alias = commandArray[1].slice(1, -1);
if (Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["g" /* removeAlias */])(alias)) {
post("Removed alias " + alias);
} else {
post("No such alias exists");
}
}
break;
default:
post("Command not found");
}
},
connectToServer: function(ip) {
console.log("Connect to server called");
var serv = Object(__WEBPACK_IMPORTED_MODULE_13__Server_js__["e" /* getServer */])(ip);
if (serv == null) {
post("Invalid server. Connection failed.");
return;
}
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = false;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].currentServer = serv.ip;
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().isConnectedTo = true;
post("Connected to " + serv.hostname);
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hostname == "darkweb") {
Object(__WEBPACK_IMPORTED_MODULE_3__DarkWeb_js__["b" /* checkIfConnectedToDarkweb */])(); //Posts a 'help' message if connecting to dark web
}
},
executeListCommand: function(commandArray) {
if (commandArray.length != 1 && commandArray.length != 2) {
post("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return;
}
//grep
var filter = null;
if (commandArray.length == 2) {
if (commandArray[1].startsWith("| grep ")) {
var pattern = commandArray[1].replace("| grep ", "");
if (pattern != " ") {
filter = pattern;
}
} else {
post("Incorrect usage of ls command. Usage: ls [| grep pattern]"); return;
}
}
//Display all programs and scripts
var allFiles = [];
//Get all of the programs and scripts on the machine into one temporary array
var s = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
for (var i = 0; i < s.programs.length; i++) {
if (filter) {
if (s.programs[i].includes(filter)) {
allFiles.push(s.programs[i]);
}
} else {
allFiles.push(s.programs[i]);
}
}
for (var i = 0; i < s.scripts.length; i++) {
if (filter) {
if (s.scripts[i].filename.includes(filter)) {
allFiles.push(s.scripts[i].filename);
}
} else {
allFiles.push(s.scripts[i].filename);
}
}
for (var i = 0; i < s.messages.length; i++) {
if (filter) {
if (s.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_8__Message_js__["a" /* Message */]) {
if (s.messages[i].filename.includes(filter)) {
allFiles.push(s.messages[i].filename);
}
} else if (s.messages[i].includes(filter)) {
allFiles.push(s.messages[i]);
}
} else {
if (s.messages[i] instanceof __WEBPACK_IMPORTED_MODULE_8__Message_js__["a" /* Message */]) {
allFiles.push(s.messages[i].filename);
} else {
allFiles.push(s.messages[i]);
}
}
}
//Sort the files alphabetically then print each
allFiles.sort();
for (var i = 0; i < allFiles.length; i++) {
post(allFiles[i]);
}
},
executeScanCommand: function(commandArray) {
if (commandArray.length != 1) {
post("Incorrect usage of netstat/scan command. Usage: netstat/scan"); return;
}
//Displays available network connections using TCP
post("Hostname IP Root Access");
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().serversOnNetwork.length; i++) {
//Add hostname
var entry = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i);
if (entry == null) {continue;}
entry = entry.hostname;
//Calculate padding and add IP
var numSpaces = 21 - entry.length;
var spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i).ip;
//Calculate padding and add root access info
var hasRoot;
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i).hasAdminRights) {
hasRoot = 'Y';
} else {
hasRoot = 'N';
}
numSpaces = 21 - __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().getServerOnNetwork(i).ip.length;
spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += hasRoot;
post(entry);
}
},
executeScanAnalyzeCommand: function(depth=1) {
//We'll use the AllServersMap as a visited() array
//TODO Using array as stack for now, can make more efficient
post("~~~~~~~~~~ Beginning scan-analyze ~~~~~~~~~~");
post(" ");
var visited = new __WEBPACK_IMPORTED_MODULE_12__Script_js__["a" /* AllServersMap */]();
var stack = [];
var depthQueue = [0];
var currServ = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
stack.push(currServ);
while(stack.length != 0) {
var s = stack.pop();
var d = depthQueue.pop();
if (visited[s.ip] || d > depth) {
continue;
} else {
visited[s.ip] = 1;
}
for (var i = s.serversOnNetwork.length-1; i >= 0; --i) {
stack.push(s.getServerOnNetwork(i));
depthQueue.push(d+1);
}
if (d == 0) {continue;} //Don't print current server
var titleDashes = Array((d-1) * 4 + 1).join("-");
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].AutoLink)) {
post("<strong>" + titleDashes + "> <a class='scan-analyze-link'>" + s.hostname + "</a></strong>", false);
} else {
post("<strong>" + titleDashes + ">" + s.hostname + "</strong>");
}
var dashes = titleDashes + "--";
//var dashes = Array(d * 2 + 1).join("-");
var c = "NO";
if (s.hasAdminRights) {c = "YES";}
post(dashes + "Root Access: " + c + ", Required hacking skill: " + s.requiredHackingSkill);
post(dashes + "Number of open ports required to NUKE: " + s.numOpenPortsRequired);
post(dashes + "RAM: " + s.maxRam);
post(" ");
}
var links = document.getElementsByClassName("scan-analyze-link");
for (var i = 0; i < links.length; ++i) {
(function() {
var hostname = links[i].innerHTML.toString();
links[i].onclick = function() {
Terminal.connectToServer(hostname);
}
}());//Immediate invocation
}
},
executeFreeCommand: function(commandArray) {
if (commandArray.length != 1) {
post("Incorrect usage of free command. Usage: free"); return;
}
post("Total: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().maxRam, 2) + " GB");
post("Used: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().ramUsed, 2) + " GB");
post("Available: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().maxRam - __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().ramUsed, 2) + " GB");
},
//First called when the "run [program]" command is called. Checks to see if you
//have the executable and, if you do, calls the executeProgram() function
runProgram: function(programName) {
//Check if you have the program on your computer. If you do, execute it, otherwise
//display an error message
var splitArgs = programName.split(" ");
var name = " ";
if (splitArgs.length > 1) {
name = splitArgs[0];
} else {
name = programName;
}
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasProgram(name)) {
Terminal.executeProgram(programName);
return;
}
post("ERROR: No such executable on home computer (Only programs that exist on your home computer can be run)");
},
//Contains the implementations of all possible programs
executeProgram: function(programName) {
var s = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer();
var splitArgs = programName.split(" ");
if (splitArgs.length > 1) {
programName = splitArgs[0];
}
switch (programName) {
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].NukeProgram:
if (s.hasAdminRights) {
post("You already have root access to this computer. There is no reason to run NUKE.exe");
} else {
if (s.openPortCount >= __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().numOpenPortsRequired) {
s.hasAdminRights = true;
post("NUKE successful! Gained root access to " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getCurrentServer().hostname);
//TODO Make this take time rather than be instant
} else {
post("NUKE unsuccessful. Not enough ports have been opened");
}
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].BruteSSHProgram:
if (s.sshPortOpen) {
post("SSH Port (22) is already open!");
} else {
s.sshPortOpen = true;
post("Opened SSH Port(22)!")
++s.openPortCount;
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].FTPCrackProgram:
if (s.ftpPortOpen) {
post("FTP Port (21) is already open!");
} else {
s.ftpPortOpen = true;
post("Opened FTP Port (21)!");
++s.openPortCount;
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram:
if (s.smtpPortOpen) {
post("SMTP Port (25) is already open!");
} else {
s.smtpPortOpen = true;
post("Opened SMTP Port (25)!");
++s.openPortCount;
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].HTTPWormProgram:
if (s.httpPortOpen) {
post("HTTP Port (80) is already open!");
} else {
s.httpPortOpen = true;
post("Opened HTTP Port (80)!");
++s.openPortCount;
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].SQLInjectProgram:
if (s.sqlPortOpen) {
post("SQL Port (1433) is already open!");
} else {
s.sqlPortOpen = true;
post("Opened SQL Port (1433)!");
++s.openPortCount;
}
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].ServerProfiler:
if (splitArgs.length != 2) {
post("Must pass a server hostname or IP as an argument for ServerProfiler.exe");
return;
}
var serv = Object(__WEBPACK_IMPORTED_MODULE_13__Server_js__["e" /* getServer */])(splitArgs[1]);
if (serv == null) {
post("Invalid server IP/hostname");
return;
}
post(serv.hostname + ":");
post("Server base security level: " + serv.baseDifficulty);
post("Server current security level: " + serv.hackDifficulty);
post("Server growth rate: " + serv.serverGrowth);
post("Netscript hack() execution time: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(scriptCalculateHackingTime(serv), 1) + "s");
post("Netscript grow() execution time: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(scriptCalculateGrowTime(serv)/1000, 1) + "s");
post("Netscript weaken() execution time: " + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(scriptCalculateWeakenTime(serv)/1000, 1) + "s");
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].AutoLink:
post("This executable cannot be run.");
post("AutoLink.exe lets you automatically connect to other servers when using 'scan-analyze'.");
post("When using scan-analyze, click on a server's hostname to connect to it.");
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV1:
post("This executable cannot be run.");
post("DeepscanV1.exe lets you run 'scan-analyze' with a depth up to 5.");
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].DeepscanV2:
post("This executable cannot be run.");
post("DeepscanV2.exe lets you run 'scan-analyze' with a depth up to 10.");
break;
case __WEBPACK_IMPORTED_MODULE_2__CreateProgram_js__["a" /* Programs */].Flight:
post("Augmentations: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].augmentations.length + " / 30");
post("Money: $" + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].money.toNumber(), 2) + " / $" + Object(__WEBPACK_IMPORTED_MODULE_15__utils_StringHelperFunctions_js__["c" /* formatNumber */])(100000000000, 2));
post("One path below must be fulfilled...");
post("----------HACKING PATH----------");
post("Hacking skill: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hacking_skill + " / 2500");
post("----------COMBAT PATH----------");
post("Strength: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].strength + " / 1500");
post("Defense: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].defense + " / 1500");
post("Dexterity: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].dexterity + " / 1500");
post("Agility: " + __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].agility + " / 1500");
break;
default:
post("Invalid executable. Cannot be run");
return;
}
},
runScript: function(scriptName) {
var server = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_12__Script_js__["d" /* 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(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["f" /* printArray */])(args) + ".");
post("May take a few seconds to start up the process...");
var runningScriptObj = new __WEBPACK_IMPORTED_MODULE_12__Script_js__["b" /* RunningScript */](script, args);
runningScriptObj.threads = numThreads;
server.runningScripts.push(runningScriptObj);
Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__["c" /* addWorkerScript */])(runningScriptObj, server);
return;
}
}
}
post("ERROR: No such script");
}
};
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return yesNoBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return yesNoTxtInpBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return yesNoBoxGetYesButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return yesNoBoxGetNoButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return yesNoTxtInpBoxGetYesButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return yesNoTxtInpBoxGetNoButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return yesNoTxtInpBoxGetInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return yesNoBoxClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return yesNoTxtInpBoxClose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return yesNoBoxOpen; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__ = __webpack_require__(1);
/* Generic Yes-No Pop-up box
* Can be used to create pop-up boxes that require a yes/no response from player
*/
var yesNoBoxOpen = false;
function yesNoBoxClose() {
var container = document.getElementById("yes-no-box-container");
if (container) {
container.style.display = "none";
} else {
console.log("ERROR: Container not found for YesNoBox");
}
yesNoBoxOpen = false;
}
function yesNoBoxGetYesButton() {
return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-yes");
}
function yesNoBoxGetNoButton() {
return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-box-no");
}
function yesNoBoxCreate(txt) {
yesNoBoxOpen = true;
var textElement = document.getElementById("yes-no-box-text");
if (textElement) {
textElement.innerHTML = txt;
}
var c = document.getElementById("yes-no-box-container");
if (c) {
c.style.display = "block";
} else {
console.log("ERROR: Container not found for YesNoBox");
}
}
/* Generic Yes-No POp-up Box with Text input */
function yesNoTxtInpBoxClose() {
var c = document.getElementById("yes-no-text-input-box-container");
if (c) {
c.style.display = "none";
} else {
console.log("ERROR: Container not found for YesNoTextInputBox");
}
yesNoBoxOpen = false;
}
function yesNoTxtInpBoxGetYesButton() {
return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-yes");
}
function yesNoTxtInpBoxGetNoButton() {
return Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["b" /* clearEventListeners */])("yes-no-text-input-box-no");
}
function yesNoTxtInpBoxGetInput() {
var val = document.getElementById("yes-no-text-input-box-input").value;
val = val.replace(/\s+/g, '');
return val;
}
function yesNoTxtInpBoxCreate(txt) {
yesNoBoxOpen = true;
var txtE = document.getElementById("yes-no-text-input-box-text");
if (txtE) {
txtE.innerHTML = txt;
}
var c = document.getElementById("yes-no-text-input-box-container");
if (c) {
c.style.display = "block";
} else {
console.log("ERROR: Container not found for YesNoTextInputBox");
}
}
/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createRandomIp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ipExists; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isValidIPAddress; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_Server_js__ = __webpack_require__(6);
/* 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 __WEBPACK_IMPORTED_MODULE_0__src_Server_js__["b" /* AllServers */]) {
if (__WEBPACK_IMPORTED_MODULE_0__src_Server_js__["b" /* 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;
}
/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return iTutorialSteps; });
/* unused harmony export iTutorialEnd */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iTutorialStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return iTutorialNextStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return currITutorialStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return iTutorialIsRunning; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__ = __webpack_require__(1);
/* InteractiveTutorial.js */
let iTutorialSteps = {
Start: "Start",
GoToCharacterPage: "Click on the Character page menu link",
CharacterPage: "Introduction to Character page",
CharacterGoToTerminalPage: "Click on the Terminal link",
TerminalIntro: "Introduction to terminal interface",
TerminalHelp: "Using the help command to display all options in terminal",
TerminalLs: "Use the ls command to show all programs/scripts. Right now we have NUKE.exe",
TerminalScan: "Using the scan command to display all available connections",
TerminalScanAnalyze1: "Use the scan-analyze command to show hacking related information",
TerminalScanAnalyze2: "Use the scan-analyze command with a depth of 3",
TerminalConnect: "Using the telnet/connect command to connect to another server",
TerminalAnalyze: "Use the analyze command to display details about this server",
TerminalNuke: "Use the NUKE Program to gain root access to a server",
TerminalManualHack: "Use the hack command to manually hack a server",
TerminalHackingMechanics: "Briefly explain hacking mechanics",
TerminalCreateScript: "Create a script using nano",
TerminalTypeScript: "This occurs in the Script Editor page...type the script then save and close",
TerminalFree: "Use the free command to check RAM",
TerminalRunScript: "Use the run command to run a script",
TerminalGoToActiveScriptsPage: "Go to the ActiveScriptsPage",
ActiveScriptsPage: "Introduction to the Active Scripts Page",
ActiveScriptsToTerminal: "Go from Active Scripts Page Back to Terminal",
TerminalTailScript: "Use the tail command to show a script's logs",
GoToHacknetNodesPage: "Go to the Hacknet Nodes page",
HacknetNodesIntroduction: "Introduction to Hacknet Nodesm and have user purchase one",
HacknetNodesGoToWorldPage: "Go to the world page",
WorldDescription: "Tell the user to explore..theres a lot of different stuff to do out there",
TutorialPageInfo: "The tutorial page contains a lot of info on different subjects",
End: "End",
}
var currITutorialStep = iTutorialSteps.Start;
var iTutorialIsRunning = false;
function iTutorialStart() {
//Don't autosave during this interactive tutorial
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 999000000000;
console.log("Interactive Tutorial started");
currITutorialStep = iTutorialSteps.Start;
iTutorialIsRunning = true;
document.getElementById("interactive-tutorial-container").style.display = "block";
iTutorialEvaluateStep();
//Exit tutorial button
var exitButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-exit");
exitButton.addEventListener("click", function() {
iTutorialEnd();
return false;
});
//Back button
var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-back");
backButton.style.display = "none";
backButton.addEventListener("click", function() {
iTutorialPrevStep();
return false;
});
}
function iTutorialEvaluateStep() {
if (!iTutorialIsRunning) {console.log("Interactive Tutorial not running"); return;}
switch(currITutorialStep) {
case iTutorialSteps.Start:
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent();
iTutorialSetText("Welcome to Bitburner, a cyberpunk-themed incremental RPG! " +
"The game takes place in a dark, dystopian future...The year is 2077...<br><br>" +
"This tutorial will show you the basics of the game to help you get started. " +
"You may skip the tutorial at any time.");
var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadCharacterContent();
iTutorialNextStep(); //Opening the character page will go to the next step
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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. A lot of content in the game is " +
"accessible only through the Terminal, and is necessary for progressing. ");
var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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 commands, how to use them, " +
"and a description of what they do. <br><br>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. <br><br> Through 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. <br><br> " +
"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). <br><br> 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.<br><br>" +
"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!<br><br> 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. <br><br> " +
"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. <br><br> For this server, the required hacking skill is only 1, " +
"which means you are able to 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.<br><br> 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. <br><br>" +
"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. <br><br> 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.<br>");
var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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! <br><br>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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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. <strong style='background-color:#444;'>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. </strong> For now, just copy " +
"and paste the following code into the script editor: <br><br>" +
"while(true) { <br>" +
"&nbsp;&nbsp;hack('foodnstuff'); <br>" +
"}<br><br> " +
"For anyone with basic programming experience, this code should be straightforward. " +
"This script will continuously hack the 'foodnstuff' server. <br><br>" +
"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. <br><br> 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 8GB 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). <br><br>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. <br><br> " +
"Let's check out some statistics of our active, 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() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadActiveScriptsContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("terminal-menu-link");
terminalMainMenuButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTerminalContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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! <br><br>" +
"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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-menu-link");
var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next");
next.style.display = "none";
hacknetNodesButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadHacknetNodesContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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. <br><br>" +
"Let's go to the 'City' page through the main navigation menu.");
document.getElementById("city-menu-link").setAttribute("class", "flashing-button");
var worldButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("city-menu-link");
worldButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadWorldContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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!<br><br>" +
"Lastly, click on the 'Tutorial' link in the main navigation menu.");
document.getElementById("tutorial-menu-link").setAttribute("class", "flashing-button");
var tutorialButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("tutorial-menu-link");
tutorialButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].loadTutorialContent();
iTutorialNextStep();
Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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. <strong style='background-color:#444;'> I know it's a lot, but I highly suggest you read " +
"(or at least skim) through this before you start playing</strong>. That's the end of the tutorial. " +
"Hope you enjoy the game!");
var next = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* clearEventListeners */])("interactive-tutorial-next");
next.style.display = "inline-block";
next.innerHTML = "Finish Tutorial";
var backButton = Object(__WEBPACK_IMPORTED_MODULE_2__utils_HelperFunctions_js__["b" /* 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
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].Counters.autoSaveCounter = 300;
console.log("Ending interactive tutorial");
__WEBPACK_IMPORTED_MODULE_0__engine_js__["Engine"].init();
currITutorialStep = iTutorialSteps.End;
iTutorialIsRunning = false;
document.getElementById("interactive-tutorial-container").style.display = "none";
Object(__WEBPACK_IMPORTED_MODULE_1__utils_DialogBox_js__["a" /* dialogBoxCreate */])("If you are new to the game, the following links may be useful for you!<br><br>" +
"<a class='a-link-button' href='http://bitburner.wikia.com/wiki/Chapt3rs_Guide_to_Getting_Started_with_Bitburner' target='_blank'>Getting Started Guide</a>" +
"<a class='a-link-button' href='http://bitburner.wikia.com/wiki/Bitburner_Wiki' target='_blank'>Wiki</a>");
}
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
}
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v7.2.3 https://github.com/MikeMcl/decimal.js/LICENCE */
;(function (globalScope) {
'use strict';
/*
* decimal.js v7.2.3
* An arbitrary-precision Decimal type for JavaScript.
* https://github.com/MikeMcl/decimal.js
* Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
* MIT Licence
*/
// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
// The maximum exponent magnitude.
// The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
var EXP_LIMIT = 9e15, // 0 to 9e15
// The limit on the value of `precision`, and on the value of the first argument to
// `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
MAX_DIGITS = 1e9, // 0 to 1e9
// Base conversion alphabet.
NUMERALS = '0123456789abcdef',
// The natural logarithm of 10 (1025 digits).
LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
// Pi (1025 digits).
PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
// The initial configuration properties of the Decimal constructor.
Decimal = {
// These values must be integers within the stated ranges (inclusive).
// Most of these values can be changed at run-time using the `Decimal.config` method.
// The maximum number of significant digits of the result of a calculation or base conversion.
// E.g. `Decimal.config({ precision: 20 });`
precision: 20, // 1 to MAX_DIGITS
// The rounding mode used when rounding to `precision`.
//
// ROUND_UP 0 Away from zero.
// ROUND_DOWN 1 Towards zero.
// ROUND_CEIL 2 Towards +Infinity.
// ROUND_FLOOR 3 Towards -Infinity.
// ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
//
// E.g.
// `Decimal.rounding = 4;`
// `Decimal.rounding = Decimal.ROUND_HALF_UP;`
rounding: 4, // 0 to 8
// The modulo mode used when calculating the modulus: a mod n.
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
// The remainder (r) is calculated as: r = a - n * q.
//
// UP 0 The remainder is positive if the dividend is negative, else is negative.
// DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
// HALF_EVEN 6 The IEEE 754 remainder function.
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
//
// Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
// division (9) are commonly used for the modulus operation. The other rounding modes can also
// be used, but they may not give useful results.
modulo: 1, // 0 to 9
// The exponent value at and beneath which `toString` returns exponential notation.
// JavaScript numbers: -7
toExpNeg: -7, // 0 to -EXP_LIMIT
// The exponent value at and above which `toString` returns exponential notation.
// JavaScript numbers: 21
toExpPos: 21, // 0 to EXP_LIMIT
// The minimum exponent value, beneath which underflow to zero occurs.
// JavaScript numbers: -324 (5e-324)
minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
// The maximum exponent value, above which overflow to Infinity occurs.
// JavaScript numbers: 308 (1.7976931348623157e+308)
maxE: EXP_LIMIT, // 1 to EXP_LIMIT
// Whether to use cryptographically-secure random number generation, if available.
crypto: false // true/false
},
// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
inexact, noConflict, quadrant,
external = true,
decimalError = '[DecimalError] ',
invalidArgument = decimalError + 'Invalid argument: ',
precisionLimitExceeded = decimalError + 'Precision limit exceeded',
cryptoUnavailable = decimalError + 'crypto unavailable',
mathfloor = Math.floor,
mathpow = Math.pow,
isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
BASE = 1e7,
LOG_BASE = 7,
MAX_SAFE_INTEGER = 9007199254740991,
LN10_PRECISION = LN10.length - 1,
PI_PRECISION = PI.length - 1,
// Decimal.prototype object
P = {};
// Decimal prototype methods
/*
* absoluteValue abs
* ceil
* comparedTo cmp
* cosine cos
* cubeRoot cbrt
* decimalPlaces dp
* dividedBy div
* dividedToIntegerBy divToInt
* equals eq
* floor
* greaterThan gt
* greaterThanOrEqualTo gte
* hyperbolicCosine cosh
* hyperbolicSine sinh
* hyperbolicTangent tanh
* inverseCosine acos
* inverseHyperbolicCosine acosh
* inverseHyperbolicSine asinh
* inverseHyperbolicTangent atanh
* inverseSine asin
* inverseTangent atan
* isFinite
* isInteger isInt
* isNaN
* isNegative isNeg
* isPositive isPos
* isZero
* lessThan lt
* lessThanOrEqualTo lte
* logarithm log
* [maximum] [max]
* [minimum] [min]
* minus sub
* modulo mod
* naturalExponential exp
* naturalLogarithm ln
* negated neg
* plus add
* precision sd
* round
* sine sin
* squareRoot sqrt
* tangent tan
* times mul
* toBinary
* toDecimalPlaces toDP
* toExponential
* toFixed
* toFraction
* toHexadecimal toHex
* toNearest
* toNumber
* toOctal
* toPower pow
* toPrecision
* toSignificantDigits toSD
* toString
* truncated trunc
* valueOf toJSON
*/
/*
* Return a new Decimal whose value is the absolute value of this Decimal.
*
*/
P.absoluteValue = P.abs = function () {
var x = new this.constructor(this);
if (x.s < 0) x.s = 1;
return finalise(x);
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
* direction of positive Infinity.
*
*/
P.ceil = function () {
return finalise(new this.constructor(this), this.e + 1, 2);
};
/*
* Return
* 1 if the value of this Decimal is greater than the value of `y`,
* -1 if the value of this Decimal is less than the value of `y`,
* 0 if they have the same value,
* NaN if the value of either Decimal is NaN.
*
*/
P.comparedTo = P.cmp = function (y) {
var i, j, xdL, ydL,
x = this,
xd = x.d,
yd = (y = new x.constructor(y)).d,
xs = x.s,
ys = y.s;
// Either NaN or ±Infinity?
if (!xd || !yd) {
return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
}
// Either zero?
if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
// Signs differ?
if (xs !== ys) return xs;
// Compare exponents.
if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
xdL = xd.length;
ydL = yd.length;
// Compare digit by digit.
for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
}
// Compare lengths.
return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
};
/*
* Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* cos(0) = 1
* cos(-0) = 1
* cos(Infinity) = NaN
* cos(-Infinity) = NaN
* cos(NaN) = NaN
*
*/
P.cosine = P.cos = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.d) return new Ctor(NaN);
// cos(0) = cos(-0) = 1
if (!x.d[0]) return new Ctor(1);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
Ctor.rounding = 1;
x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
};
/*
*
* Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* cbrt(0) = 0
* cbrt(-0) = -0
* cbrt(1) = 1
* cbrt(-1) = -1
* cbrt(N) = N
* cbrt(-I) = -I
* cbrt(I) = I
*
* Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
*
*/
P.cubeRoot = P.cbrt = function () {
var e, m, n, r, rep, s, sd, t, t3, t3plusx,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
external = false;
// Initial estimate.
s = x.s * Math.pow(x.s * x, 1 / 3);
// Math.cbrt underflow/overflow?
// Pass x to Math.pow as integer, then adjust the exponent of the result.
if (!s || Math.abs(s) == 1 / 0) {
n = digitsToString(x.d);
e = x.e;
// Adjust n exponent so it is a multiple of 3 away from x exponent.
if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
s = Math.pow(n, 1 / 3);
// Rarely, e may be one less than the result exponent value.
e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
if (s == 1 / 0) {
n = '5e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
}
r = new Ctor(n);
r.s = x.s;
} else {
r = new Ctor(s.toString());
}
sd = (e = Ctor.precision) + 3;
// Halley's method.
// TODO? Compare Newton's method.
for (;;) {
t = r;
t3 = t.times(t).times(t);
t3plusx = t3.plus(x);
r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
// TODO? Replace with for-loop and checkRoundingDigits.
if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
n = n.slice(sd - 3, sd + 1);
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
// , i.e. approaching a rounding boundary, continue the iteration.
if (n == '9999' || !rep && n == '4999') {
// On the first iteration only, check to see if rounding up gives the exact result as the
// nines may infinitely repeat.
if (!rep) {
finalise(t, e + 1, 0);
if (t.times(t).times(t).eq(x)) {
r = t;
break;
}
}
sd += 4;
rep = 1;
} else {
// If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
// If not, then there are further digits and m will be truthy.
if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
// Truncate to the first rounding digit.
finalise(r, e + 1, 1);
m = !r.times(r).times(r).eq(x);
}
break;
}
}
}
external = true;
return finalise(r, e, Ctor.rounding, m);
};
/*
* Return the number of decimal places of the value of this Decimal.
*
*/
P.decimalPlaces = P.dp = function () {
var w,
d = this.d,
n = NaN;
if (d) {
w = d.length - 1;
n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
// Subtract the number of trailing zeros of the last word.
w = d[w];
if (w) for (; w % 10 == 0; w /= 10) n--;
if (n < 0) n = 0;
}
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
*/
P.dividedBy = P.div = function (y) {
return divide(this, new this.constructor(y));
};
/*
* Return a new Decimal whose value is the integer part of dividing the value of this Decimal
* by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
*
*/
P.dividedToIntegerBy = P.divToInt = function (y) {
var x = this,
Ctor = x.constructor;
return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
};
/*
* Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
*
*/
P.equals = P.eq = function (y) {
return this.cmp(y) === 0;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
* direction of negative Infinity.
*
*/
P.floor = function () {
return finalise(new this.constructor(this), this.e + 1, 3);
};
/*
* Return true if the value of this Decimal is greater than the value of `y`, otherwise return
* false.
*
*/
P.greaterThan = P.gt = function (y) {
return this.cmp(y) > 0;
};
/*
* Return true if the value of this Decimal is greater than or equal to the value of `y`,
* otherwise return false.
*
*/
P.greaterThanOrEqualTo = P.gte = function (y) {
var k = this.cmp(y);
return k == 1 || k === 0;
};
/*
* Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [1, Infinity]
*
* cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
*
* cosh(0) = 1
* cosh(-0) = 1
* cosh(Infinity) = Infinity
* cosh(-Infinity) = Infinity
* cosh(NaN) = NaN
*
* x time taken (ms) result
* 1000 9 9.8503555700852349694e+433
* 10000 25 4.4034091128314607936e+4342
* 100000 171 1.4033316802130615897e+43429
* 1000000 3817 1.5166076984010437725e+434294
* 10000000 abandoned after 2 minute wait
*
* TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
*
*/
P.hyperbolicCosine = P.cosh = function () {
var k, n, pr, rm, len,
x = this,
Ctor = x.constructor,
one = new Ctor(1);
if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
if (x.isZero()) return one;
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
Ctor.rounding = 1;
len = x.d.length;
// Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
// i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
// Estimate the optimum number of times to use the argument reduction.
// TODO? Estimation reused from cosine() and may not be optimal here.
if (len < 32) {
k = Math.ceil(len / 3);
n = Math.pow(4, -k).toString();
} else {
k = 16;
n = '2.3283064365386962890625e-10';
}
x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
// Reverse argument reduction
var cosh2_x,
i = k,
d8 = new Ctor(8);
for (; i--;) {
cosh2_x = x.times(x);
x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
}
return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
};
/*
* Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
*
* sinh(0) = 0
* sinh(-0) = -0
* sinh(Infinity) = Infinity
* sinh(-Infinity) = -Infinity
* sinh(NaN) = NaN
*
* x time taken (ms)
* 10 2 ms
* 100 5 ms
* 1000 14 ms
* 10000 82 ms
* 100000 886 ms 1.4033316802130615897e+43429
* 200000 2613 ms
* 300000 5407 ms
* 400000 8824 ms
* 500000 13026 ms 8.7080643612718084129e+217146
* 1000000 48543 ms
*
* TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
*
*/
P.hyperbolicSine = P.sinh = function () {
var k, pr, rm, len,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
Ctor.rounding = 1;
len = x.d.length;
if (len < 3) {
x = taylorSeries(Ctor, 2, x, x, true);
} else {
// Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
// i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
// 3 multiplications and 1 addition
// Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
// i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
// 4 multiplications and 2 additions
// Estimate the optimum number of times to use the argument reduction.
k = 1.4 * Math.sqrt(len);
k = k > 16 ? 16 : k | 0;
x = x.times(Math.pow(5, -k));
x = taylorSeries(Ctor, 2, x, x, true);
// Reverse argument reduction
var sinh2_x,
d5 = new Ctor(5),
d16 = new Ctor(16),
d20 = new Ctor(20);
for (; k--;) {
sinh2_x = x.times(x);
x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
}
}
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(x, pr, rm, true);
};
/*
* Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* tanh(x) = sinh(x) / cosh(x)
*
* tanh(0) = 0
* tanh(-0) = -0
* tanh(Infinity) = 1
* tanh(-Infinity) = -1
* tanh(NaN) = NaN
*
*/
P.hyperbolicTangent = P.tanh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(x.s);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 7;
Ctor.rounding = 1;
return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
};
/*
* Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
* this Decimal.
*
* Domain: [-1, 1]
* Range: [0, pi]
*
* acos(x) = pi/2 - asin(x)
*
* acos(0) = pi/2
* acos(-0) = pi/2
* acos(1) = 0
* acos(-1) = pi
* acos(1/2) = pi/3
* acos(-1/2) = 2*pi/3
* acos(|x| > 1) = NaN
* acos(NaN) = NaN
*
*/
P.inverseCosine = P.acos = function () {
var halfPi,
x = this,
Ctor = x.constructor,
k = x.abs().cmp(1),
pr = Ctor.precision,
rm = Ctor.rounding;
if (k !== -1) {
return k === 0
// |x| is 1
? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
// |x| > 1 or x is NaN
: new Ctor(NaN);
}
if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
// TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
Ctor.precision = pr + 6;
Ctor.rounding = 1;
x = x.asin();
halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
Ctor.precision = pr;
Ctor.rounding = rm;
return halfPi.minus(x);
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
* value of this Decimal.
*
* Domain: [1, Infinity]
* Range: [0, Infinity]
*
* acosh(x) = ln(x + sqrt(x^2 - 1))
*
* acosh(x < 1) = NaN
* acosh(NaN) = NaN
* acosh(Infinity) = Infinity
* acosh(-Infinity) = NaN
* acosh(0) = NaN
* acosh(-0) = NaN
* acosh(1) = 0
* acosh(-1) = NaN
*
*/
P.inverseHyperbolicCosine = P.acosh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
if (!x.isFinite()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
Ctor.rounding = 1;
external = false;
x = x.times(x).minus(1).sqrt().plus(x);
external = true;
Ctor.precision = pr;
Ctor.rounding = rm;
return x.ln();
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
* of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* asinh(x) = ln(x + sqrt(x^2 + 1))
*
* asinh(NaN) = NaN
* asinh(Infinity) = Infinity
* asinh(-Infinity) = -Infinity
* asinh(0) = 0
* asinh(-0) = -0
*
*/
P.inverseHyperbolicSine = P.asinh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
Ctor.rounding = 1;
external = false;
x = x.times(x).plus(1).sqrt().plus(x);
external = true;
Ctor.precision = pr;
Ctor.rounding = rm;
return x.ln();
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
* value of this Decimal.
*
* Domain: [-1, 1]
* Range: [-Infinity, Infinity]
*
* atanh(x) = 0.5 * ln((1 + x) / (1 - x))
*
* atanh(|x| > 1) = NaN
* atanh(NaN) = NaN
* atanh(Infinity) = NaN
* atanh(-Infinity) = NaN
* atanh(0) = 0
* atanh(-0) = -0
* atanh(1) = Infinity
* atanh(-1) = -Infinity
*
*/
P.inverseHyperbolicTangent = P.atanh = function () {
var pr, rm, wpr, xsd,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
pr = Ctor.precision;
rm = Ctor.rounding;
xsd = x.sd();
if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
Ctor.precision = wpr = xsd - x.e;
x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
Ctor.precision = pr + 4;
Ctor.rounding = 1;
x = x.ln();
Ctor.precision = pr;
Ctor.rounding = rm;
return x.times(0.5);
};
/*
* Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi/2, pi/2]
*
* asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
*
* asin(0) = 0
* asin(-0) = -0
* asin(1/2) = pi/6
* asin(-1/2) = -pi/6
* asin(1) = pi/2
* asin(-1) = -pi/2
* asin(|x| > 1) = NaN
* asin(NaN) = NaN
*
* TODO? Compare performance of Taylor series.
*
*/
P.inverseSine = P.asin = function () {
var halfPi, k,
pr, rm,
x = this,
Ctor = x.constructor;
if (x.isZero()) return new Ctor(x);
k = x.abs().cmp(1);
pr = Ctor.precision;
rm = Ctor.rounding;
if (k !== -1) {
// |x| is 1
if (k === 0) {
halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
halfPi.s = x.s;
return halfPi;
}
// |x| > 1 or x is NaN
return new Ctor(NaN);
}
// TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
Ctor.precision = pr + 6;
Ctor.rounding = 1;
x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
Ctor.precision = pr;
Ctor.rounding = rm;
return x.times(2);
};
/*
* Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
* of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi/2, pi/2]
*
* atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
*
* atan(0) = 0
* atan(-0) = -0
* atan(1) = pi/4
* atan(-1) = -pi/4
* atan(Infinity) = pi/2
* atan(-Infinity) = -pi/2
* atan(NaN) = NaN
*
*/
P.inverseTangent = P.atan = function () {
var i, j, k, n, px, t, r, wpr, x2,
x = this,
Ctor = x.constructor,
pr = Ctor.precision,
rm = Ctor.rounding;
if (!x.isFinite()) {
if (!x.s) return new Ctor(NaN);
if (pr + 4 <= PI_PRECISION) {
r = getPi(Ctor, pr + 4, rm).times(0.5);
r.s = x.s;
return r;
}
} else if (x.isZero()) {
return new Ctor(x);
} else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
r = getPi(Ctor, pr + 4, rm).times(0.25);
r.s = x.s;
return r;
}
Ctor.precision = wpr = pr + 10;
Ctor.rounding = 1;
// TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
// Argument reduction
// Ensure |x| < 0.42
// atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
k = Math.min(28, wpr / LOG_BASE + 2 | 0);
for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
external = false;
j = Math.ceil(wpr / LOG_BASE);
n = 1;
x2 = x.times(x);
r = new Ctor(x);
px = x;
// atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
for (; i !== -1;) {
px = px.times(x2);
t = r.minus(px.div(n += 2));
px = px.times(x2);
r = t.plus(px.div(n += 2));
if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
}
if (k) r = r.times(2 << (k - 1));
external = true;
return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
};
/*
* Return true if the value of this Decimal is a finite number, otherwise return false.
*
*/
P.isFinite = function () {
return !!this.d;
};
/*
* Return true if the value of this Decimal is an integer, otherwise return false.
*
*/
P.isInteger = P.isInt = function () {
return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
};
/*
* Return true if the value of this Decimal is NaN, otherwise return false.
*
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this Decimal is negative, otherwise return false.
*
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this Decimal is positive, otherwise return false.
*
*/
P.isPositive = P.isPos = function () {
return this.s > 0;
};
/*
* Return true if the value of this Decimal is 0 or -0, otherwise return false.
*
*/
P.isZero = function () {
return !!this.d && this.d[0] === 0;
};
/*
* Return true if the value of this Decimal is less than `y`, otherwise return false.
*
*/
P.lessThan = P.lt = function (y) {
return this.cmp(y) < 0;
};
/*
* Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
*
*/
P.lessThanOrEqualTo = P.lte = function (y) {
return this.cmp(y) < 1;
};
/*
* Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* If no base is specified, return log[10](arg).
*
* log[base](arg) = ln(arg) / ln(base)
*
* The result will always be correctly rounded if the base of the log is 10, and 'almost always'
* otherwise:
*
* Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
* rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
* between the result and the correctly rounded result will be one ulp (unit in the last place).
*
* log[-b](a) = NaN
* log[0](a) = NaN
* log[1](a) = NaN
* log[NaN](a) = NaN
* log[Infinity](a) = NaN
* log[b](0) = -Infinity
* log[b](-0) = -Infinity
* log[b](-a) = NaN
* log[b](1) = 0
* log[b](Infinity) = Infinity
* log[b](NaN) = NaN
*
* [base] {number|string|Decimal} The base of the logarithm.
*
*/
P.logarithm = P.log = function (base) {
var isBase10, d, denominator, k, inf, num, sd, r,
arg = this,
Ctor = arg.constructor,
pr = Ctor.precision,
rm = Ctor.rounding,
guard = 5;
// Default base is 10.
if (base == null) {
base = new Ctor(10);
isBase10 = true;
} else {
base = new Ctor(base);
d = base.d;
// Return NaN if base is negative, or non-finite, or is 0 or 1.
if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
isBase10 = base.eq(10);
}
d = arg.d;
// Is arg negative, non-finite, 0 or 1?
if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
}
// The result will have a non-terminating decimal expansion if base is 10 and arg is not an
// integer power of 10.
if (isBase10) {
if (d.length > 1) {
inf = true;
} else {
for (k = d[0]; k % 10 === 0;) k /= 10;
inf = k !== 1;
}
}
external = false;
sd = pr + guard;
num = naturalLogarithm(arg, sd);
denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
// The result will have 5 rounding digits.
r = divide(num, denominator, sd, 1);
// If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
// calculate 10 further digits.
//
// If the result is known to have an infinite decimal expansion, repeat this until it is clear
// that the result is above or below the boundary. Otherwise, if after calculating the 10
// further digits, the last 14 are nines, round up and assume the result is exact.
// Also assume the result is exact if the last 14 are zero.
//
// Example of a result that will be incorrectly rounded:
// log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
// The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
// will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
// the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
// place is still 2.6.
if (checkRoundingDigits(r.d, k = pr, rm)) {
do {
sd += 10;
num = naturalLogarithm(arg, sd);
denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
r = divide(num, denominator, sd, 1);
if (!inf) {
// Check for 14 nines from the 2nd rounding digit, as the first may be 4.
if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
r = finalise(r, pr + 1, 0);
}
break;
}
} while (checkRoundingDigits(r.d, k += 10, rm));
}
external = true;
return finalise(r, pr, rm);
};
/*
* Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
*
* arguments {number|string|Decimal}
*
P.max = function () {
Array.prototype.push.call(arguments, this);
return maxOrMin(this.constructor, arguments, 'lt');
};
*/
/*
* Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
*
* arguments {number|string|Decimal}
*
P.min = function () {
Array.prototype.push.call(arguments, this);
return maxOrMin(this.constructor, arguments, 'gt');
};
*/
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.minus = P.sub = function (y) {
var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// If either is not finite...
if (!x.d || !y.d) {
// Return NaN if either is NaN.
if (!x.s || !y.s) y = new Ctor(NaN);
// Return y negated if x is finite and y is ±Infinity.
else if (x.d) y.s = -y.s;
// Return x if y is finite and x is ±Infinity.
// Return x if both are ±Infinity with different signs.
// Return NaN if both are ±Infinity with the same sign.
else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
return y;
}
// If signs differ...
if (x.s != y.s) {
y.s = -y.s;
return x.plus(y);
}
xd = x.d;
yd = y.d;
pr = Ctor.precision;
rm = Ctor.rounding;
// If either is zero...
if (!xd[0] || !yd[0]) {
// Return y negated if x is zero and y is non-zero.
if (yd[0]) y.s = -y.s;
// Return x if y is zero and x is non-zero.
else if (xd[0]) y = new Ctor(x);
// Return zero if both are zero.
// From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
else return new Ctor(rm === 3 ? -0 : 0);
return external ? finalise(y, pr, rm) : y;
}
// x and y are finite, non-zero numbers with the same sign.
// Calculate base 1e7 exponents.
e = mathfloor(y.e / LOG_BASE);
xe = mathfloor(x.e / LOG_BASE);
xd = xd.slice();
k = xe - e;
// If base 1e7 exponents differ...
if (k) {
xLTy = k < 0;
if (xLTy) {
d = xd;
k = -k;
len = yd.length;
} else {
d = yd;
e = xe;
len = xd.length;
}
// Numbers with massively different exponents would result in a very high number of
// zeros needing to be prepended, but this can be avoided while still ensuring correct
// rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
if (k > i) {
k = i;
d.length = 1;
}
// Prepend zeros to equalise exponents.
d.reverse();
for (i = k; i--;) d.push(0);
d.reverse();
// Base 1e7 exponents equal.
} else {
// Check digits to determine which is the bigger number.
i = xd.length;
len = yd.length;
xLTy = i < len;
if (xLTy) len = i;
for (i = 0; i < len; i++) {
if (xd[i] != yd[i]) {
xLTy = xd[i] < yd[i];
break;
}
}
k = 0;
}
if (xLTy) {
d = xd;
xd = yd;
yd = d;
y.s = -y.s;
}
len = xd.length;
// Append zeros to `xd` if shorter.
// Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
// Subtract yd from xd.
for (i = yd.length; i > k;) {
if (xd[--i] < yd[i]) {
for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
--xd[j];
xd[i] += BASE;
}
xd[i] -= yd[i];
}
// Remove trailing zeros.
for (; xd[--len] === 0;) xd.pop();
// Remove leading zeros and adjust exponent accordingly.
for (; xd[0] === 0; xd.shift()) --e;
// Zero?
if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
y.d = xd;
y.e = getBase10Exponent(xd, e);
return external ? finalise(y, pr, rm) : y;
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* The result depends on the modulo mode.
*
*/
P.modulo = P.mod = function (y) {
var q,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
// Return x if y is ±Infinity or x is ±0.
if (!y.d || x.d && !x.d[0]) {
return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
}
// Prevent rounding of intermediate calculations.
external = false;
if (Ctor.modulo == 9) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// result = x - q * y where 0 <= result < abs(y)
q = divide(x, y.abs(), 0, 3, 1);
q.s *= y.s;
} else {
q = divide(x, y, 0, Ctor.modulo, 1);
}
q = q.times(y);
external = true;
return x.minus(q);
};
/*
* Return a new Decimal whose value is the natural exponential of the value of this Decimal,
* i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.naturalExponential = P.exp = function () {
return naturalExponential(this);
};
/*
* Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
* rounded to `precision` significant digits using rounding mode `rounding`.
*
*/
P.naturalLogarithm = P.ln = function () {
return naturalLogarithm(this);
};
/*
* Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
* -1.
*
*/
P.negated = P.neg = function () {
var x = new this.constructor(this);
x.s = -x.s;
return finalise(x);
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.plus = P.add = function (y) {
var carry, d, e, i, k, len, pr, rm, xd, yd,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// If either is not finite...
if (!x.d || !y.d) {
// Return NaN if either is NaN.
if (!x.s || !y.s) y = new Ctor(NaN);
// Return x if y is finite and x is ±Infinity.
// Return x if both are ±Infinity with the same sign.
// Return NaN if both are ±Infinity with different signs.
// Return y if x is finite and y is ±Infinity.
else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
return y;
}
// If signs differ...
if (x.s != y.s) {
y.s = -y.s;
return x.minus(y);
}
xd = x.d;
yd = y.d;
pr = Ctor.precision;
rm = Ctor.rounding;
// If either is zero...
if (!xd[0] || !yd[0]) {
// Return x if y is zero.
// Return y if y is non-zero.
if (!yd[0]) y = new Ctor(x);
return external ? finalise(y, pr, rm) : y;
}
// x and y are finite, non-zero numbers with the same sign.
// Calculate base 1e7 exponents.
k = mathfloor(x.e / LOG_BASE);
e = mathfloor(y.e / LOG_BASE);
xd = xd.slice();
i = k - e;
// If base 1e7 exponents differ...
if (i) {
if (i < 0) {
d = xd;
i = -i;
len = yd.length;
} else {
d = yd;
e = k;
len = xd.length;
}
// Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
k = Math.ceil(pr / LOG_BASE);
len = k > len ? k + 1 : len + 1;
if (i > len) {
i = len;
d.length = 1;
}
// Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
d.reverse();
for (; i--;) d.push(0);
d.reverse();
}
len = xd.length;
i = yd.length;
// If yd is longer than xd, swap xd and yd so xd points to the longer array.
if (len - i < 0) {
i = len;
d = yd;
yd = xd;
xd = d;
}
// Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
for (carry = 0; i;) {
carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
xd[i] %= BASE;
}
if (carry) {
xd.unshift(carry);
++e;
}
// Remove trailing zeros.
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
for (len = xd.length; xd[--len] == 0;) xd.pop();
y.d = xd;
y.e = getBase10Exponent(xd, e);
return external ? finalise(y, pr, rm) : y;
};
/*
* Return the number of significant digits of the value of this Decimal.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*
*/
P.precision = P.sd = function (z) {
var k,
x = this;
if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
if (x.d) {
k = getPrecision(x.d);
if (z && x.e + 1 > k) k = x.e + 1;
} else {
k = NaN;
}
return k;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
* rounding mode `rounding`.
*
*/
P.round = function () {
var x = this,
Ctor = x.constructor;
return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
};
/*
* Return a new Decimal whose value is the sine of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* sin(x) = x - x^3/3! + x^5/5! - ...
*
* sin(0) = 0
* sin(-0) = -0
* sin(Infinity) = NaN
* sin(-Infinity) = NaN
* sin(NaN) = NaN
*
*/
P.sine = P.sin = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
Ctor.rounding = 1;
x = sine(Ctor, toLessThanHalfPi(Ctor, x));
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
};
/*
* Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* sqrt(-n) = N
* sqrt(N) = N
* sqrt(-I) = N
* sqrt(I) = I
* sqrt(0) = 0
* sqrt(-0) = -0
*
*/
P.squareRoot = P.sqrt = function () {
var m, n, sd, r, rep, t,
x = this,
d = x.d,
e = x.e,
s = x.s,
Ctor = x.constructor;
// Negative/NaN/Infinity/zero?
if (s !== 1 || !d || !d[0]) {
return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
}
external = false;
// Initial estimate.
s = Math.sqrt(+x);
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if (s == 0 || s == 1 / 0) {
n = digitsToString(d);
if ((n.length + e) % 2 == 0) n += '0';
s = Math.sqrt(n);
e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
if (s == 1 / 0) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
}
r = new Ctor(n);
} else {
r = new Ctor(s.toString());
}
sd = (e = Ctor.precision) + 3;
// Newton-Raphson iteration.
for (;;) {
t = r;
r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
// TODO? Replace with for-loop and checkRoundingDigits.
if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
n = n.slice(sd - 3, sd + 1);
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
// 4999, i.e. approaching a rounding boundary, continue the iteration.
if (n == '9999' || !rep && n == '4999') {
// On the first iteration only, check to see if rounding up gives the exact result as the
// nines may infinitely repeat.
if (!rep) {
finalise(t, e + 1, 0);
if (t.times(t).eq(x)) {
r = t;
break;
}
}
sd += 4;
rep = 1;
} else {
// If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
// If not, then there are further digits and m will be truthy.
if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
// Truncate to the first rounding digit.
finalise(r, e + 1, 1);
m = !r.times(r).eq(x);
}
break;
}
}
}
external = true;
return finalise(r, e, Ctor.rounding, m);
};
/*
* Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* tan(0) = 0
* tan(-0) = -0
* tan(Infinity) = NaN
* tan(-Infinity) = NaN
* tan(NaN) = NaN
*
*/
P.tangent = P.tan = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 10;
Ctor.rounding = 1;
x = x.sin();
x.s = 1;
x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
*/
P.times = P.mul = function (y) {
var carry, e, i, k, r, rL, t, xdL, ydL,
x = this,
Ctor = x.constructor,
xd = x.d,
yd = (y = new Ctor(y)).d;
y.s *= x.s;
// If either is NaN, ±Infinity or ±0...
if (!xd || !xd[0] || !yd || !yd[0]) {
return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
// Return NaN if either is NaN.
// Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
? NaN
// Return ±Infinity if either is ±Infinity.
// Return ±0 if either is ±0.
: !xd || !yd ? y.s / 0 : y.s * 0);
}
e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
xdL = xd.length;
ydL = yd.length;
// Ensure xd points to the longer array.
if (xdL < ydL) {
r = xd;
xd = yd;
yd = r;
rL = xdL;
xdL = ydL;
ydL = rL;
}
// Initialise the result array with zeros.
r = [];
rL = xdL + ydL;
for (i = rL; i--;) r.push(0);
// Multiply!
for (i = ydL; --i >= 0;) {
carry = 0;
for (k = xdL + i; k > i;) {
t = r[k] + yd[i] * xd[k - i - 1] + carry;
r[k--] = t % BASE | 0;
carry = t / BASE | 0;
}
r[k] = (r[k] + carry) % BASE | 0;
}
// Remove trailing zeros.
for (; !r[--rL];) r.pop();
if (carry) ++e;
else r.shift();
y.d = r;
y.e = getBase10Exponent(r, e);
return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
};
/*
* Return a string representing the value of this Decimal in base 2, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toBinary = function (sd, rm) {
return toStringBinary(this, 2, sd, rm);
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
* decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
*
* If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toDecimalPlaces = P.toDP = function (dp, rm) {
var x = this,
Ctor = x.constructor;
x = new Ctor(x);
if (dp === void 0) return x;
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
return finalise(x, dp + x.e + 1, rm);
};
/*
* Return a string representing the value of this Decimal in exponential notation rounded to
* `dp` fixed decimal places using rounding mode `rounding`.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toExponential = function (dp, rm) {
var str,
x = this,
Ctor = x.constructor;
if (dp === void 0) {
str = finiteToString(x, true);
} else {
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = finalise(new Ctor(x), dp + 1, rm);
str = finiteToString(x, true, dp + 1);
}
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a string representing the value of this Decimal in normal (fixed-point) notation to
* `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
* omitted.
*
* As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
* (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
* (-0).toFixed(3) is '0.000'.
* (-0.5).toFixed(0) is '-0'.
*
*/
P.toFixed = function (dp, rm) {
var str, y,
x = this,
Ctor = x.constructor;
if (dp === void 0) {
str = finiteToString(x);
} else {
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
y = finalise(new Ctor(x), dp + x.e + 1, rm);
str = finiteToString(y, false, dp + y.e + 1);
}
// To determine whether to add the minus sign look at the value before it was rounded,
// i.e. look at `x` rather than `y`.
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return an array representing the value of this Decimal as a simple fraction with an integer
* numerator and an integer denominator.
*
* The denominator will be a positive non-zero value less than or equal to the specified maximum
* denominator. If a maximum denominator is not specified, the denominator will be the lowest
* value necessary to represent the number exactly.
*
* [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
*
*/
P.toFraction = function (maxD) {
var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
x = this,
xd = x.d,
Ctor = x.constructor;
if (!xd) return new Ctor(x);
n1 = d0 = new Ctor(1);
d1 = n0 = new Ctor(0);
d = new Ctor(d1);
e = d.e = getPrecision(xd) - x.e - 1;
k = e % LOG_BASE;
d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
if (maxD == null) {
// d is 10**e, the minimum max-denominator needed.
maxD = e > 0 ? d : n1;
} else {
n = new Ctor(maxD);
if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
}
external = false;
n = new Ctor(digitsToString(xd));
pr = Ctor.precision;
Ctor.precision = e = xd.length * LOG_BASE * 2;
for (;;) {
q = divide(n, d, 0, 1, 1);
d2 = d0.plus(q.times(d1));
if (d2.cmp(maxD) == 1) break;
d0 = d1;
d1 = d2;
d2 = n1;
n1 = n0.plus(q.times(d2));
n0 = d2;
d2 = d;
d = n.minus(q.times(d2));
n = d2;
}
d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
n0 = n0.plus(d2.times(n1));
d0 = d0.plus(d2.times(d1));
n0.s = n1.s = x.s;
// Determine which fraction is closer to x, n0/d0 or n1/d1?
r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
? [n1, d1] : [n0, d0];
Ctor.precision = pr;
external = true;
return r;
};
/*
* Return a string representing the value of this Decimal in base 16, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toHexadecimal = P.toHex = function (sd, rm) {
return toStringBinary(this, 16, sd, rm);
};
/*
* Returns a new Decimal whose value is the nearest multiple of the magnitude of `y` to the value
* of this Decimal.
*
* If the value of this Decimal is equidistant from two multiples of `y`, the rounding mode `rm`,
* or `Decimal.rounding` if `rm` is omitted, determines the direction of the nearest multiple.
*
* In the context of this method, rounding mode 4 (ROUND_HALF_UP) is the same as rounding mode 0
* (ROUND_UP), and so on.
*
* The return value will always have the same sign as this Decimal, unless either this Decimal
* or `y` is NaN, in which case the return value will be also be NaN.
*
* The return value is not affected by the value of `precision`.
*
* y {number|string|Decimal} The magnitude to round to a multiple of.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toNearest() rounding mode not an integer: {rm}'
* 'toNearest() rounding mode out of range: {rm}'
*
*/
P.toNearest = function (y, rm) {
var x = this,
Ctor = x.constructor;
x = new Ctor(x);
if (y == null) {
// If x is not finite, return x.
if (!x.d) return x;
y = new Ctor(1);
rm = Ctor.rounding;
} else {
y = new Ctor(y);
if (rm !== void 0) checkInt32(rm, 0, 8);
// If x is not finite, return x if y is not NaN, else NaN.
if (!x.d) return y.s ? x : y;
// If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
if (!y.d) {
if (y.s) y.s = x.s;
return y;
}
}
// If y is not zero, calculate the nearest multiple of y to x.
if (y.d[0]) {
external = false;
if (rm < 4) rm = [4, 5, 7, 8][rm];
x = divide(x, y, 0, rm, 1).times(y);
external = true;
finalise(x);
// If y is zero, return zero with the sign of x.
} else {
y.s = x.s;
x = y;
}
return x;
};
/*
* Return the value of this Decimal converted to a number primitive.
* Zero keeps its sign.
*
*/
P.toNumber = function () {
return +this;
};
/*
* Return a string representing the value of this Decimal in base 8, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toOctal = function (sd, rm) {
return toStringBinary(this, 8, sd, rm);
};
/*
* Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
* to `precision` significant digits using rounding mode `rounding`.
*
* ECMAScript compliant.
*
* pow(x, NaN) = NaN
* pow(x, ±0) = 1
* pow(NaN, non-zero) = NaN
* pow(abs(x) > 1, +Infinity) = +Infinity
* pow(abs(x) > 1, -Infinity) = +0
* pow(abs(x) == 1, ±Infinity) = NaN
* pow(abs(x) < 1, +Infinity) = +0
* pow(abs(x) < 1, -Infinity) = +Infinity
* pow(+Infinity, y > 0) = +Infinity
* pow(+Infinity, y < 0) = +0
* pow(-Infinity, odd integer > 0) = -Infinity
* pow(-Infinity, even integer > 0) = +Infinity
* pow(-Infinity, odd integer < 0) = -0
* pow(-Infinity, even integer < 0) = +0
* pow(+0, y > 0) = +0
* pow(+0, y < 0) = +Infinity
* pow(-0, odd integer > 0) = -0
* pow(-0, even integer > 0) = +0
* pow(-0, odd integer < 0) = -Infinity
* pow(-0, even integer < 0) = +Infinity
* pow(finite x < 0, finite non-integer) = NaN
*
* For non-integer or very large exponents pow(x, y) is calculated using
*
* x^y = exp(y*ln(x))
*
* Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
* probability of an incorrectly rounded result
* P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
* i.e. 1 in 250,000,000,000,000
*
* If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
*
* y {number|string|Decimal} The power to which to raise this Decimal.
*
*/
P.toPower = P.pow = function (y) {
var e, k, pr, r, rm, s,
x = this,
Ctor = x.constructor,
yn = +(y = new Ctor(y));
// Either ±Infinity, NaN or ±0?
if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
x = new Ctor(x);
if (x.eq(1)) return x;
pr = Ctor.precision;
rm = Ctor.rounding;
if (y.eq(1)) return finalise(x, pr, rm);
// y exponent
e = mathfloor(y.e / LOG_BASE);
// If y is a small integer use the 'exponentiation by squaring' algorithm.
if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
r = intPow(Ctor, x, k, pr);
return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
}
s = x.s;
// if x is negative
if (s < 0) {
// if y is not an integer
if (e < y.d.length - 1) return new Ctor(NaN);
// Result is positive if x is negative and the last digit of integer y is even.
if ((y.d[e] & 1) == 0) s = 1;
// if x.eq(-1)
if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {
x.s = s;
return x;
}
}
// Estimate result exponent.
// x^y = 10^e, where e = y * log10(x)
// log10(x) = log10(x_significand) + x_exponent
// log10(x_significand) = ln(x_significand) / ln(10)
k = mathpow(+x, yn);
e = k == 0 || !isFinite(k)
? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
: new Ctor(k + '').e;
// Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
// Overflow/underflow?
if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);
external = false;
Ctor.rounding = x.s = 1;
// Estimate the extra guard digits needed to ensure five correct rounding digits from
// naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
// new Decimal(2.32456).pow('2087987436534566.46411')
// should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
k = Math.min(12, (e + '').length);
// r = x^y = exp(y*ln(x))
r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
// r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)
if (r.d) {
// Truncate to the required precision plus five rounding digits.
r = finalise(r, pr + 5, 1);
// If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
// the result.
if (checkRoundingDigits(r.d, pr, rm)) {
e = pr + 10;
// Truncate to the increased precision plus five rounding digits.
r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
// Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
r = finalise(r, pr + 1, 0);
}
}
}
r.s = s;
external = true;
Ctor.rounding = rm;
return finalise(r, pr, rm);
};
/*
* Return a string representing the value of this Decimal rounded to `sd` significant digits
* using rounding mode `rounding`.
*
* Return exponential notation if `sd` is less than the number of digits necessary to represent
* the integer part of the value in normal notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toPrecision = function (sd, rm) {
var str,
x = this,
Ctor = x.constructor;
if (sd === void 0) {
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = finalise(new Ctor(x), sd, rm);
str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
}
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
* significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
* omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toSD() digits out of range: {sd}'
* 'toSD() digits not an integer: {sd}'
* 'toSD() rounding mode not an integer: {rm}'
* 'toSD() rounding mode out of range: {rm}'
*
*/
P.toSignificantDigits = P.toSD = function (sd, rm) {
var x = this,
Ctor = x.constructor;
if (sd === void 0) {
sd = Ctor.precision;
rm = Ctor.rounding;
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
}
return finalise(new Ctor(x), sd, rm);
};
/*
* Return a string representing the value of this Decimal.
*
* Return exponential notation if this Decimal has a positive exponent equal to or greater than
* `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
*
*/
P.toString = function () {
var x = this,
Ctor = x.constructor,
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
*
*/
P.truncated = P.trunc = function () {
return finalise(new this.constructor(this), this.e + 1, 1);
};
/*
* Return a string representing the value of this Decimal.
* Unlike `toString`, negative zero will include the minus sign.
*
*/
P.valueOf = P.toJSON = function () {
var x = this,
Ctor = x.constructor,
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
return x.isNeg() ? '-' + str : str;
};
/*
// Add aliases to match BigDecimal method names.
// P.add = P.plus;
P.subtract = P.minus;
P.multiply = P.times;
P.divide = P.div;
P.remainder = P.mod;
P.compareTo = P.cmp;
P.negate = P.neg;
*/
// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
/*
* digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,
* finiteToString, naturalExponential, naturalLogarithm
* checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
* P.toPrecision, P.toSignificantDigits, toStringBinary, random
* checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
* convertBase toStringBinary, parseOther
* cos P.cos
* divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
* P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
* P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
* taylorSeries, atan2, parseOther
* finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
* P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
* P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
* P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
* P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
* P.truncated, divide, getLn10, getPi, naturalExponential,
* naturalLogarithm, ceil, floor, round, trunc
* finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
* toStringBinary
* getBase10Exponent P.minus, P.plus, P.times, parseOther
* getLn10 P.logarithm, naturalLogarithm
* getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
* getPrecision P.precision, P.toFraction
* getZeroString digitsToString, finiteToString
* intPow P.toPower, parseOther
* isOdd toLessThanHalfPi
* maxOrMin max, min
* naturalExponential P.naturalExponential, P.toPower
* naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
* P.toPower, naturalExponential
* nonFiniteToString finiteToString, toStringBinary
* parseDecimal Decimal
* parseOther Decimal
* sin P.sin
* taylorSeries P.cosh, P.sinh, cos, sin
* toLessThanHalfPi P.cos, P.sin
* toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
* truncate intPow
*
* Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
* naturalLogarithm, config, parseOther, random, Decimal
*/
function digitsToString(d) {
var i, k, ws,
indexOfLastWord = d.length - 1,
str = '',
w = d[0];
if (indexOfLastWord > 0) {
str += w;
for (i = 1; i < indexOfLastWord; i++) {
ws = d[i] + '';
k = LOG_BASE - ws.length;
if (k) str += getZeroString(k);
str += ws;
}
w = d[i];
ws = w + '';
k = LOG_BASE - ws.length;
if (k) str += getZeroString(k);
} else if (w === 0) {
return '0';
}
// Remove trailing zeros of last w.
for (; w % 10 === 0;) w /= 10;
return str + w;
}
function checkInt32(i, min, max) {
if (i !== ~~i || i < min || i > max) {
throw Error(invalidArgument + i);
}
}
/*
* Check 5 rounding digits if `repeating` is null, 4 otherwise.
* `repeating == null` if caller is `log` or `pow`,
* `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
*/
function checkRoundingDigits(d, i, rm, repeating) {
var di, k, r, rd;
// Get the length of the first word of the array d.
for (k = d[0]; k >= 10; k /= 10) --i;
// Is the rounding digit in the first word of d?
if (--i < 0) {
i += LOG_BASE;
di = 0;
} else {
di = Math.ceil((i + 1) / LOG_BASE);
i %= LOG_BASE;
}
// i is the index (0 - 6) of the rounding digit.
// E.g. if within the word 3487563 the first rounding digit is 5,
// then i = 4, k = 1000, rd = 3487563 % 1000 = 563
k = mathpow(10, LOG_BASE - i);
rd = d[di] % k | 0;
if (repeating == null) {
if (i < 3) {
if (i == 0) rd = rd / 100 | 0;
else if (i == 1) rd = rd / 10 | 0;
r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
} else {
r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
(d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
(rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
}
} else {
if (i < 4) {
if (i == 0) rd = rd / 1000 | 0;
else if (i == 1) rd = rd / 100 | 0;
else if (i == 2) rd = rd / 10 | 0;
r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
} else {
r = ((repeating || rm < 4) && rd + 1 == k ||
(!repeating && rm > 3) && rd + 1 == k / 2) &&
(d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
}
}
return r;
}
// Convert string of `baseIn` to an array of numbers of `baseOut`.
// Eg. convertBase('255', 10, 16) returns [15, 15].
// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
function convertBase(str, baseIn, baseOut) {
var j,
arr = [0],
arrL,
i = 0,
strL = str.length;
for (; i < strL;) {
for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
arr[0] += NUMERALS.indexOf(str.charAt(i++));
for (j = 0; j < arr.length; j++) {
if (arr[j] > baseOut - 1) {
if (arr[j + 1] === void 0) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
/*
* cos(x) = 1 - x^2/2! + x^4/4! - ...
* |x| < pi/2
*
*/
function cosine(Ctor, x) {
var k, y,
len = x.d.length;
// Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
// i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
// Estimate the optimum number of times to use the argument reduction.
if (len < 32) {
k = Math.ceil(len / 3);
y = Math.pow(4, -k).toString();
} else {
k = 16;
y = '2.3283064365386962890625e-10';
}
Ctor.precision += k;
x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
// Reverse argument reduction
for (var i = k; i--;) {
var cos2x = x.times(x);
x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
}
Ctor.precision -= k;
return x;
}
/*
* Perform division in the specified base.
*/
var divide = (function () {
// Assumes non-zero x and k, and hence non-zero result.
function multiplyInteger(x, k, base) {
var temp,
carry = 0,
i = x.length;
for (x = x.slice(); i--;) {
temp = x[i] * k + carry;
x[i] = temp % base | 0;
carry = temp / base | 0;
}
if (carry) x.unshift(carry);
return x;
}
function compare(a, b, aL, bL) {
var i, r;
if (aL != bL) {
r = aL > bL ? 1 : -1;
} else {
for (i = r = 0; i < aL; i++) {
if (a[i] != b[i]) {
r = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return r;
}
function subtract(a, b, aL, base) {
var i = 0;
// Subtract b from a.
for (; aL--;) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for (; !a[0] && a.length > 1;) a.shift();
}
return function (x, y, pr, rm, dp, base) {
var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
yL, yz,
Ctor = x.constructor,
sign = x.s == y.s ? 1 : -1,
xd = x.d,
yd = y.d;
// Either NaN, Infinity or 0?
if (!xd || !xd[0] || !yd || !yd[0]) {
return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
// Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
}
if (base) {
logBase = 1;
e = x.e - y.e;
} else {
base = BASE;
logBase = LOG_BASE;
e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
}
yL = yd.length;
xL = xd.length;
q = new Ctor(sign);
qd = q.d = [];
// Result exponent may be one less than e.
// The digit array of a Decimal from toStringBinary may have trailing zeros.
for (i = 0; yd[i] == (xd[i] || 0); i++);
if (yd[i] > (xd[i] || 0)) e--;
if (pr == null) {
sd = pr = Ctor.precision;
rm = Ctor.rounding;
} else if (dp) {
sd = pr + (x.e - y.e) + 1;
} else {
sd = pr;
}
if (sd < 0) {
qd.push(1);
more = true;
} else {
// Convert precision in number of base 10 digits to base 1e7 digits.
sd = sd / logBase + 2 | 0;
i = 0;
// divisor < 1e7
if (yL == 1) {
k = 0;
yd = yd[0];
sd++;
// k is the carry.
for (; (i < xL || k) && sd--; i++) {
t = k * base + (xd[i] || 0);
qd[i] = t / yd | 0;
k = t % yd | 0;
}
more = k || i < xL;
// divisor >= 1e7
} else {
// Normalise xd and yd so highest order digit of yd is >= base/2
k = base / (yd[0] + 1) | 0;
if (k > 1) {
yd = multiplyInteger(yd, k, base);
xd = multiplyInteger(xd, k, base);
yL = yd.length;
xL = xd.length;
}
xi = yL;
rem = xd.slice(0, yL);
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for (; remL < yL;) rem[remL++] = 0;
yz = yd.slice();
yz.unshift(0);
yd0 = yd[0];
if (yd[1] >= base / 2) ++yd0;
do {
k = 0;
// Compare divisor and remainder.
cmp = compare(yd, rem, yL, remL);
// If divisor < remainder.
if (cmp < 0) {
// Calculate trial digit, k.
rem0 = rem[0];
if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
// k will be how many times the divisor goes into the current remainder.
k = rem0 / yd0 | 0;
// Algorithm:
// 1. product = divisor * trial digit (k)
// 2. if product > remainder: product -= divisor, k--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, k++
if (k > 1) {
if (k >= base) k = base - 1;
// product = divisor * trial digit.
prod = multiplyInteger(yd, k, base);
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
cmp = compare(prod, rem, prodL, remL);
// product > remainder.
if (cmp == 1) {
k--;
// Subtract divisor from product.
subtract(prod, yL < prodL ? yz : yd, prodL, base);
}
} else {
// cmp is -1.
// If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
// to avoid it. If k is 1 there is a need to compare yd and rem again below.
if (k == 0) cmp = k = 1;
prod = yd.slice();
}
prodL = prod.length;
if (prodL < remL) prod.unshift(0);
// Subtract product from remainder.
subtract(rem, prod, remL, base);
// If product was < previous remainder.
if (cmp == -1) {
remL = rem.length;
// Compare divisor and new remainder.
cmp = compare(yd, rem, yL, remL);
// If divisor < new remainder, subtract divisor from remainder.
if (cmp < 1) {
k++;
// Subtract divisor from remainder.
subtract(rem, yL < remL ? yz : yd, remL, base);
}
}
remL = rem.length;
} else if (cmp === 0) {
k++;
rem = [0];
} // if cmp === 1, k will be 0
// Add the next digit, k, to the result array.
qd[i++] = k;
// Update the remainder.
if (cmp && rem[0]) {
rem[remL++] = xd[xi] || 0;
} else {
rem = [xd[xi]];
remL = 1;
}
} while ((xi++ < xL || rem[0] !== void 0) && sd--);
more = rem[0] !== void 0;
}
// Leading zero?
if (!qd[0]) qd.shift();
}
// logBase is 1 when divide is being used for base conversion.
if (logBase == 1) {
q.e = e;
inexact = more;
} else {
// To calculate q.e, first get the number of digits of qd[0].
for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
q.e = i + e * logBase - 1;
finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
}
return q;
};
})();
/*
* Round `x` to `sd` significant digits using rounding mode `rm`.
* Check for over/under-flow.
*/
function finalise(x, sd, rm, isTruncated) {
var digits, i, j, k, rd, roundUp, w, xd, xdi,
Ctor = x.constructor;
// Don't round if sd is null or undefined.
out: if (sd != null) {
xd = x.d;
// Infinity/NaN.
if (!xd) return x;
// rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
// w: the word of xd containing rd, a base 1e7 number.
// xdi: the index of w within xd.
// digits: the number of digits of w.
// i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
// they had leading zeros)
// j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
// Get the length of the first word of the digits array xd.
for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
i = sd - digits;
// Is the rounding digit in the first word of xd?
if (i < 0) {
i += LOG_BASE;
j = sd;
w = xd[xdi = 0];
// Get the rounding digit at index j of w.
rd = w / mathpow(10, digits - j - 1) % 10 | 0;
} else {
xdi = Math.ceil((i + 1) / LOG_BASE);
k = xd.length;
if (xdi >= k) {
if (isTruncated) {
// Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
for (; k++ <= xdi;) xd.push(0);
w = rd = 0;
digits = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
w = k = xd[xdi];
// Get the number of digits of w.
for (digits = 1; k >= 10; k /= 10) digits++;
// Get the index of rd within w.
i %= LOG_BASE;
// Get the index of rd within w, adjusted for leading zeros.
// The number of leading zeros of w is given by LOG_BASE - digits.
j = i - LOG_BASE + digits;
// Get the rounding digit at index j of w.
rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
}
}
// Are there any non-zero digits after the rounding digit?
isTruncated = isTruncated || sd < 0 ||
xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
// The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
// of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
// will give 714.
roundUp = rm < 4
? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
: rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
rm == (x.s < 0 ? 8 : 7));
if (sd < 1 || !xd[0]) {
xd.length = 0;
if (roundUp) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
x.e = -sd || 0;
} else {
// Zero.
xd[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if (i == 0) {
xd.length = xdi;
k = 1;
xdi--;
} else {
xd.length = xdi + 1;
k = mathpow(10, LOG_BASE - i);
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of w.
xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
}
if (roundUp) {
for (;;) {
// Is the digit to be rounded up in the first word of xd?
if (xdi == 0) {
// i will be the length of xd[0] before k is added.
for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
j = xd[0] += k;
for (k = 1; j >= 10; j /= 10) k++;
// if i != k the length has increased.
if (i != k) {
x.e++;
if (xd[0] == BASE) xd[0] = 1;
}
break;
} else {
xd[xdi] += k;
if (xd[xdi] != BASE) break;
xd[xdi--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for (i = xd.length; xd[--i] === 0;) xd.pop();
}
if (external) {
// Overflow?
if (x.e > Ctor.maxE) {
// Infinity.
x.d = null;
x.e = NaN;
// Underflow?
} else if (x.e < Ctor.minE) {
// Zero.
x.e = 0;
x.d = [0];
// Ctor.underflow = true;
} // else Ctor.underflow = false;
}
return x;
}
function finiteToString(x, isExp, sd) {
if (!x.isFinite()) return nonFiniteToString(x);
var k,
e = x.e,
str = digitsToString(x.d),
len = str.length;
if (isExp) {
if (sd && (k = sd - len) > 0) {
str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
} else if (len > 1) {
str = str.charAt(0) + '.' + str.slice(1);
}
str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
} else if (e < 0) {
str = '0.' + getZeroString(-e - 1) + str;
if (sd && (k = sd - len) > 0) str += getZeroString(k);
} else if (e >= len) {
str += getZeroString(e + 1 - len);
if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
} else {
if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
if (sd && (k = sd - len) > 0) {
if (e + 1 === len) str += '.';
str += getZeroString(k);
}
}
return str;
}
// Calculate the base 10 exponent from the base 1e7 exponent.
function getBase10Exponent(digits, e) {
var w = digits[0];
// Add the number of digits of the first word of the digits array.
for ( e *= LOG_BASE; w >= 10; w /= 10) e++;
return e;
}
function getLn10(Ctor, sd, pr) {
if (sd > LN10_PRECISION) {
// Reset global state in case the exception is caught.
external = true;
if (pr) Ctor.precision = pr;
throw Error(precisionLimitExceeded);
}
return finalise(new Ctor(LN10), sd, 1, true);
}
function getPi(Ctor, sd, rm) {
if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
return finalise(new Ctor(PI), sd, rm, true);
}
function getPrecision(digits) {
var w = digits.length - 1,
len = w * LOG_BASE + 1;
w = digits[w];
// If non-zero...
if (w) {
// Subtract the number of trailing zeros of the last word.
for (; w % 10 == 0; w /= 10) len--;
// Add the number of digits of the first word.
for (w = digits[0]; w >= 10; w /= 10) len++;
}
return len;
}
function getZeroString(k) {
var zs = '';
for (; k--;) zs += '0';
return zs;
}
/*
* Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
* integer of type number.
*
* Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
*
*/
function intPow(Ctor, x, n, pr) {
var isTruncated,
r = new Ctor(1),
// Max n of 9007199254740991 takes 53 loop iterations.
// Maximum digits array length; leaves [28, 34] guard digits.
k = Math.ceil(pr / LOG_BASE + 4);
external = false;
for (;;) {
if (n % 2) {
r = r.times(x);
if (truncate(r.d, k)) isTruncated = true;
}
n = mathfloor(n / 2);
if (n === 0) {
// To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
n = r.d.length - 1;
if (isTruncated && r.d[n] === 0) ++r.d[n];
break;
}
x = x.times(x);
truncate(x.d, k);
}
external = true;
return r;
}
function isOdd(n) {
return n.d[n.d.length - 1] & 1;
}
/*
* Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
*/
function maxOrMin(Ctor, args, ltgt) {
var y,
x = new Ctor(args[0]),
i = 0;
for (; ++i < args.length;) {
y = new Ctor(args[i]);
if (!y.s) {
x = y;
break;
} else if (x[ltgt](y)) {
x = y;
}
}
return x;
}
/*
* Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
* digits.
*
* Taylor/Maclaurin series.
*
* exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
*
* Argument reduction:
* Repeat x = x / 32, k += 5, until |x| < 0.1
* exp(x) = exp(x / 2^k)^(2^k)
*
* Previously, the argument was initially reduced by
* exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
* to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
* found to be slower than just dividing repeatedly by 32 as above.
*
* Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
* Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
* (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
*
* exp(Infinity) = Infinity
* exp(-Infinity) = 0
* exp(NaN) = NaN
* exp(±0) = 1
*
* exp(x) is non-terminating for any finite, non-zero x.
*
* The result will always be correctly rounded.
*
*/
function naturalExponential(x, sd) {
var denominator, guard, j, pow, sum, t, wpr,
rep = 0,
i = 0,
k = 0,
Ctor = x.constructor,
rm = Ctor.rounding,
pr = Ctor.precision;
// 0/NaN/Infinity?
if (!x.d || !x.d[0] || x.e > 17) {
return new Ctor(x.d
? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
: x.s ? x.s < 0 ? 0 : x : 0 / 0);
}
if (sd == null) {
external = false;
wpr = pr;
} else {
wpr = sd;
}
t = new Ctor(0.03125);
// while abs(x) >= 0.1
while (x.e > -2) {
// x = x / 2^5
x = x.times(t);
k += 5;
}
// Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
// necessary to ensure the first 4 rounding digits are correct.
guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
wpr += guard;
denominator = pow = sum = new Ctor(1);
Ctor.precision = wpr;
for (;;) {
pow = finalise(pow.times(x), wpr, 1);
denominator = denominator.times(++i);
t = sum.plus(divide(pow, denominator, wpr, 1));
if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
j = k;
while (j--) sum = finalise(sum.times(sum), wpr, 1);
// Check to see if the first 4 rounding digits are [49]999.
// If so, repeat the summation with a higher precision, otherwise
// e.g. with precision: 18, rounding: 1
// exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
// `wpr - guard` is the index of first rounding digit.
if (sd == null) {
if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
Ctor.precision = wpr += 10;
denominator = pow = t = new Ctor(1);
i = 0;
rep++;
} else {
return finalise(sum, Ctor.precision = pr, rm, external = true);
}
} else {
Ctor.precision = pr;
return sum;
}
}
sum = t;
}
}
/*
* Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
* digits.
*
* ln(-n) = NaN
* ln(0) = -Infinity
* ln(-0) = -Infinity
* ln(1) = 0
* ln(Infinity) = Infinity
* ln(-Infinity) = NaN
* ln(NaN) = NaN
*
* ln(n) (n != 1) is non-terminating.
*
*/
function naturalLogarithm(y, sd) {
var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
n = 1,
guard = 10,
x = y,
xd = x.d,
Ctor = x.constructor,
rm = Ctor.rounding,
pr = Ctor.precision;
// Is x negative or Infinity, NaN, 0 or 1?
if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
}
if (sd == null) {
external = false;
wpr = pr;
} else {
wpr = sd;
}
Ctor.precision = wpr += guard;
c = digitsToString(xd);
c0 = c.charAt(0);
if (Math.abs(e = x.e) < 1.5e15) {
// Argument reduction.
// The series converges faster the closer the argument is to 1, so using
// ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
// multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
// 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
// later be divided by this number, then separate out the power of 10 using
// ln(a*10^b) = ln(a) + b*ln(10).
// max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
//while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
// max n is 6 (gives 0.7 - 1.3)
while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
x = x.times(y);
c = digitsToString(x.d);
c0 = c.charAt(0);
n++;
}
e = x.e;
if (c0 > 1) {
x = new Ctor('0.' + c);
e++;
} else {
x = new Ctor(c0 + '.' + c.slice(1));
}
} else {
// The argument reduction method above may result in overflow if the argument y is a massive
// number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
// function using ln(x*10^e) = ln(x) + e*ln(10).
t = getLn10(Ctor, wpr + 2, pr).times(e + '');
x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
Ctor.precision = pr;
return sd == null ? finalise(x, pr, rm, external = true) : x;
}
// x1 is x reduced to a value near 1.
x1 = x;
// Taylor series.
// ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
// where x = (y - 1)/(y + 1) (|x| < 1)
sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
x2 = finalise(x.times(x), wpr, 1);
denominator = 3;
for (;;) {
numerator = finalise(numerator.times(x2), wpr, 1);
t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
sum = sum.times(2);
// Reverse the argument reduction. Check that e is not 0 because, besides preventing an
// unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
sum = divide(sum, new Ctor(n), wpr, 1);
// Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
// been repeated previously) and the first 4 rounding digits 9999?
// If so, restart the summation with a higher precision, otherwise
// e.g. with precision: 12, rounding: 1
// ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
// `wpr - guard` is the index of first rounding digit.
if (sd == null) {
if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
Ctor.precision = wpr += guard;
t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
x2 = finalise(x.times(x), wpr, 1);
denominator = rep = 1;
} else {
return finalise(sum, Ctor.precision = pr, rm, external = true);
}
} else {
Ctor.precision = pr;
return sum;
}
}
sum = t;
denominator += 2;
}
}
// ±Infinity, NaN.
function nonFiniteToString(x) {
// Unsigned.
return String(x.s * x.s / 0);
}
/*
* Parse the value of a new Decimal `x` from string `str`.
*/
function parseDecimal(x, str) {
var e, i, len;
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
// Exponential form?
if ((i = str.search(/e/i)) > 0) {
// Determine exponent.
if (e < 0) e = i;
e += +str.slice(i + 1);
str = str.substring(0, i);
} else if (e < 0) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for (i = 0; str.charCodeAt(i) === 48; i++);
// Determine trailing zeros.
for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
str = str.slice(i, len);
if (str) {
len -= i;
x.e = e = e - i - 1;
x.d = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first word of the digits array.
i = (e + 1) % LOG_BASE;
if (e < 0) i += LOG_BASE;
if (i < len) {
if (i) x.d.push(+str.slice(0, i));
for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for (; i--;) str += '0';
x.d.push(+str);
if (external) {
// Overflow?
if (x.e > x.constructor.maxE) {
// Infinity.
x.d = null;
x.e = NaN;
// Underflow?
} else if (x.e < x.constructor.minE) {
// Zero.
x.e = 0;
x.d = [0];
// x.constructor.underflow = true;
} // else x.constructor.underflow = false;
}
} else {
// Zero.
x.e = 0;
x.d = [0];
}
return x;
}
/*
* Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
*/
function parseOther(x, str) {
var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
if (str === 'Infinity' || str === 'NaN') {
if (!+str) x.s = NaN;
x.e = NaN;
x.d = null;
return x;
}
if (isHex.test(str)) {
base = 16;
str = str.toLowerCase();
} else if (isBinary.test(str)) {
base = 2;
} else if (isOctal.test(str)) {
base = 8;
} else {
throw Error(invalidArgument + str);
}
// Is there a binary exponent part?
i = str.search(/p/i);
if (i > 0) {
p = +str.slice(i + 1);
str = str.substring(2, i);
} else {
str = str.slice(2);
}
// Convert `str` as an integer then divide the result by `base` raised to a power such that the
// fraction part will be restored.
i = str.indexOf('.');
isFloat = i >= 0;
Ctor = x.constructor;
if (isFloat) {
str = str.replace('.', '');
len = str.length;
i = len - i;
// log[10](16) = 1.2041... , log[10](88) = 1.9444....
divisor = intPow(Ctor, new Ctor(base), i, i * 2);
}
xd = convertBase(str, base, BASE);
xe = xd.length - 1;
// Remove trailing zeros.
for (i = xe; xd[i] === 0; --i) xd.pop();
if (i < 0) return new Ctor(x.s * 0);
x.e = getBase10Exponent(xd, xe);
x.d = xd;
external = false;
// At what precision to perform the division to ensure exact conversion?
// maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
// log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
// E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
// maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
// Therefore using 4 * the number of digits of str will always be enough.
if (isFloat) x = divide(x, divisor, len * 4);
// Multiply by the binary exponent part if present.
if (p) x = x.times(Math.abs(p) < 54 ? Math.pow(2, p) : Decimal.pow(2, p));
external = true;
return x;
}
/*
* sin(x) = x - x^3/3! + x^5/5! - ...
* |x| < pi/2
*
*/
function sine(Ctor, x) {
var k,
len = x.d.length;
if (len < 3) return taylorSeries(Ctor, 2, x, x);
// Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
// i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
// and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
// Estimate the optimum number of times to use the argument reduction.
k = 1.4 * Math.sqrt(len);
k = k > 16 ? 16 : k | 0;
// Max k before Math.pow precision loss is 22
x = x.times(Math.pow(5, -k));
x = taylorSeries(Ctor, 2, x, x);
// Reverse argument reduction
var sin2_x,
d5 = new Ctor(5),
d16 = new Ctor(16),
d20 = new Ctor(20);
for (; k--;) {
sin2_x = x.times(x);
x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
}
return x;
}
// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
function taylorSeries(Ctor, n, x, y, isHyperbolic) {
var j, t, u, x2,
i = 1,
pr = Ctor.precision,
k = Math.ceil(pr / LOG_BASE);
external = false;
x2 = x.times(x);
u = new Ctor(y);
for (;;) {
t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
u = isHyperbolic ? y.plus(t) : y.minus(t);
y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
t = u.plus(y);
if (t.d[k] !== void 0) {
for (j = k; t.d[j] === u.d[j] && j--;);
if (j == -1) break;
}
j = u;
u = y;
y = t;
t = j;
i++;
}
external = true;
t.d.length = k + 1;
return t;
}
// Return the absolute value of `x` reduced to less than or equal to half pi.
function toLessThanHalfPi(Ctor, x) {
var t,
isNeg = x.s < 0,
pi = getPi(Ctor, Ctor.precision, 1),
halfPi = pi.times(0.5);
x = x.abs();
if (x.lte(halfPi)) {
quadrant = isNeg ? 4 : 1;
return x;
}
t = x.divToInt(pi);
if (t.isZero()) {
quadrant = isNeg ? 3 : 2;
} else {
x = x.minus(t.times(pi));
// 0 <= x < pi
if (x.lte(halfPi)) {
quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
return x;
}
quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
}
return x.minus(pi).abs();
}
/*
* Return the value of Decimal `x` as a string in base `baseOut`.
*
* If the optional `sd` argument is present include a binary exponent suffix.
*/
function toStringBinary(x, baseOut, sd, rm) {
var base, e, i, k, len, roundUp, str, xd, y,
Ctor = x.constructor,
isExp = sd !== void 0;
if (isExp) {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
} else {
sd = Ctor.precision;
rm = Ctor.rounding;
}
if (!x.isFinite()) {
str = nonFiniteToString(x);
} else {
str = finiteToString(x);
i = str.indexOf('.');
// Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
// maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
// minBinaryExponent = floor(decimalExponent * log[2](10))
// log[2](10) = 3.321928094887362347870319429489390175864
if (isExp) {
base = 2;
if (baseOut == 16) {
sd = sd * 4 - 3;
} else if (baseOut == 8) {
sd = sd * 3 - 2;
}
} else {
base = baseOut;
}
// Convert the number as an integer then divide the result by its base raised to a power such
// that the fraction part will be restored.
// Non-integer.
if (i >= 0) {
str = str.replace('.', '');
y = new Ctor(1);
y.e = str.length - i;
y.d = convertBase(finiteToString(y), 10, base);
y.e = y.d.length;
}
xd = convertBase(str, 10, base);
e = len = xd.length;
// Remove trailing zeros.
for (; xd[--len] == 0;) xd.pop();
if (!xd[0]) {
str = isExp ? '0p+0' : '0';
} else {
if (i < 0) {
e--;
} else {
x = new Ctor(x);
x.d = xd;
x.e = e;
x = divide(x, y, sd, rm, 0, base);
xd = x.d;
e = x.e;
roundUp = inexact;
}
// The rounding digit, i.e. the digit after the digit that may be rounded up.
i = xd[sd];
k = base / 2;
roundUp = roundUp || xd[sd + 1] !== void 0;
roundUp = rm < 4
? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
: i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
rm === (x.s < 0 ? 8 : 7));
xd.length = sd;
if (roundUp) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for (; ++xd[--sd] > base - 1;) {
xd[sd] = 0;
if (!sd) {
++e;
xd.unshift(1);
}
}
}
// Determine trailing zeros.
for (len = xd.length; !xd[len - 1]; --len);
// E.g. [4, 11, 15] becomes 4bf.
for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
// Add binary exponent suffix?
if (isExp) {
if (len > 1) {
if (baseOut == 16 || baseOut == 8) {
i = baseOut == 16 ? 4 : 3;
for (--len; len % i; len++) str += '0';
xd = convertBase(str, base, baseOut);
for (len = xd.length; !xd[len - 1]; --len);
// xd[0] will always be be 1
for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
} else {
str = str.charAt(0) + '.' + str.slice(1);
}
}
str = str + (e < 0 ? 'p' : 'p+') + e;
} else if (e < 0) {
for (; ++e;) str = '0' + str;
str = '0.' + str;
} else {
if (++e > len) for (e -= len; e-- ;) str += '0';
else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
}
}
str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
}
return x.s < 0 ? '-' + str : str;
}
// Does not strip trailing zeros.
function truncate(arr, len) {
if (arr.length > len) {
arr.length = len;
return true;
}
}
// Decimal methods
/*
* abs
* acos
* acosh
* add
* asin
* asinh
* atan
* atanh
* atan2
* cbrt
* ceil
* clone
* config
* cos
* cosh
* div
* exp
* floor
* hypot
* ln
* log
* log2
* log10
* max
* min
* mod
* mul
* pow
* random
* round
* set
* sign
* sin
* sinh
* sqrt
* sub
* tan
* tanh
* trunc
*/
/*
* Return a new Decimal whose value is the absolute value of `x`.
*
* x {number|string|Decimal}
*
*/
function abs(x) {
return new this(x).abs();
}
/*
* Return a new Decimal whose value is the arccosine in radians of `x`.
*
* x {number|string|Decimal}
*
*/
function acos(x) {
return new this(x).acos();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function acosh(x) {
return new this(x).acosh();
}
/*
* Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function add(x, y) {
return new this(x).plus(y);
}
/*
* Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function asin(x) {
return new this(x).asin();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function asinh(x) {
return new this(x).asinh();
}
/*
* Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function atan(x) {
return new this(x).atan();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function atanh(x) {
return new this(x).atanh();
}
/*
* Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
* (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi, pi]
*
* y {number|string|Decimal} The y-coordinate.
* x {number|string|Decimal} The x-coordinate.
*
* atan2(±0, -0) = ±pi
* atan2(±0, +0) = ±0
* atan2(±0, -x) = ±pi for x > 0
* atan2(±0, x) = ±0 for x > 0
* atan2(-y, ±0) = -pi/2 for y > 0
* atan2(y, ±0) = pi/2 for y > 0
* atan2(±y, -Infinity) = ±pi for finite y > 0
* atan2(±y, +Infinity) = ±0 for finite y > 0
* atan2(±Infinity, x) = ±pi/2 for finite x
* atan2(±Infinity, -Infinity) = ±3*pi/4
* atan2(±Infinity, +Infinity) = ±pi/4
* atan2(NaN, x) = NaN
* atan2(y, NaN) = NaN
*
*/
function atan2(y, x) {
y = new this(y);
x = new this(x);
var r,
pr = this.precision,
rm = this.rounding,
wpr = pr + 4;
// Either NaN
if (!y.s || !x.s) {
r = new this(NaN);
// Both ±Infinity
} else if (!y.d && !x.d) {
r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
r.s = y.s;
// x is ±Infinity or y is ±0
} else if (!x.d || y.isZero()) {
r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
r.s = y.s;
// y is ±Infinity or x is ±0
} else if (!y.d || x.isZero()) {
r = getPi(this, wpr, 1).times(0.5);
r.s = y.s;
// Both non-zero and finite
} else if (x.s < 0) {
this.precision = wpr;
this.rounding = 1;
r = this.atan(divide(y, x, wpr, 1));
x = getPi(this, wpr, 1);
this.precision = pr;
this.rounding = rm;
r = y.s < 0 ? r.minus(x) : r.plus(x);
} else {
r = this.atan(divide(y, x, wpr, 1));
}
return r;
}
/*
* Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function cbrt(x) {
return new this(x).cbrt();
}
/*
* Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
*
* x {number|string|Decimal}
*
*/
function ceil(x) {
return finalise(x = new this(x), x.e + 1, 2);
}
/*
* Configure global settings for a Decimal constructor.
*
* `obj` is an object with one or more of the following properties,
*
* precision {number}
* rounding {number}
* toExpNeg {number}
* toExpPos {number}
* maxE {number}
* minE {number}
* modulo {number}
* crypto {boolean|number}
*
* E.g. Decimal.config({ precision: 20, rounding: 4 })
*
*/
function config(obj) {
if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
var i, p, v,
ps = [
'precision', 1, MAX_DIGITS,
'rounding', 0, 8,
'toExpNeg', -EXP_LIMIT, 0,
'toExpPos', 0, EXP_LIMIT,
'maxE', 0, EXP_LIMIT,
'minE', -EXP_LIMIT, 0,
'modulo', 0, 9
];
for (i = 0; i < ps.length; i += 3) {
if ((v = obj[p = ps[i]]) !== void 0) {
if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
else throw Error(invalidArgument + p + ': ' + v);
}
}
if ((v = obj[p = 'crypto']) !== void 0) {
if (v === true || v === false || v === 0 || v === 1) {
if (v) {
if (typeof crypto != 'undefined' && crypto &&
(crypto.getRandomValues || crypto.randomBytes)) {
this[p] = true;
} else {
throw Error(cryptoUnavailable);
}
} else {
this[p] = false;
}
} else {
throw Error(invalidArgument + p + ': ' + v);
}
}
return this;
}
/*
* Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function cos(x) {
return new this(x).cos();
}
/*
* Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function cosh(x) {
return new this(x).cosh();
}
/*
* Create and return a Decimal constructor with the same configuration properties as this Decimal
* constructor.
*
*/
function clone(obj) {
var i, p, ps;
/*
* The Decimal constructor and exported function.
* Return a new Decimal instance.
*
* v {number|string|Decimal} A numeric value.
*
*/
function Decimal(v) {
var e, i, t,
x = this;
// Decimal called without new.
if (!(x instanceof Decimal)) return new Decimal(v);
// Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
// which points to Object.
x.constructor = Decimal;
// Duplicate.
if (v instanceof Decimal) {
x.s = v.s;
x.e = v.e;
x.d = (v = v.d) ? v.slice() : v;
return;
}
t = typeof v;
if (t === 'number') {
if (v === 0) {
x.s = 1 / v < 0 ? -1 : 1;
x.e = 0;
x.d = [0];
return;
}
if (v < 0) {
v = -v;
x.s = -1;
} else {
x.s = 1;
}
// Fast path for small integers.
if (v === ~~v && v < 1e7) {
for (e = 0, i = v; i >= 10; i /= 10) e++;
x.e = e;
x.d = [v];
return;
// Infinity, NaN.
} else if (v * 0 !== 0) {
if (!v) x.s = NaN;
x.e = NaN;
x.d = null;
return;
}
return parseDecimal(x, v.toString());
} else if (t !== 'string') {
throw Error(invalidArgument + v);
}
// Minus sign?
if (v.charCodeAt(0) === 45) {
v = v.slice(1);
x.s = -1;
} else {
x.s = 1;
}
return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
}
Decimal.prototype = P;
Decimal.ROUND_UP = 0;
Decimal.ROUND_DOWN = 1;
Decimal.ROUND_CEIL = 2;
Decimal.ROUND_FLOOR = 3;
Decimal.ROUND_HALF_UP = 4;
Decimal.ROUND_HALF_DOWN = 5;
Decimal.ROUND_HALF_EVEN = 6;
Decimal.ROUND_HALF_CEIL = 7;
Decimal.ROUND_HALF_FLOOR = 8;
Decimal.EUCLID = 9;
Decimal.config = Decimal.set = config;
Decimal.clone = clone;
Decimal.abs = abs;
Decimal.acos = acos;
Decimal.acosh = acosh; // ES6
Decimal.add = add;
Decimal.asin = asin;
Decimal.asinh = asinh; // ES6
Decimal.atan = atan;
Decimal.atanh = atanh; // ES6
Decimal.atan2 = atan2;
Decimal.cbrt = cbrt; // ES6
Decimal.ceil = ceil;
Decimal.cos = cos;
Decimal.cosh = cosh; // ES6
Decimal.div = div;
Decimal.exp = exp;
Decimal.floor = floor;
Decimal.hypot = hypot; // ES6
Decimal.ln = ln;
Decimal.log = log;
Decimal.log10 = log10; // ES6
Decimal.log2 = log2; // ES6
Decimal.max = max;
Decimal.min = min;
Decimal.mod = mod;
Decimal.mul = mul;
Decimal.pow = pow;
Decimal.random = random;
Decimal.round = round;
Decimal.sign = sign; // ES6
Decimal.sin = sin;
Decimal.sinh = sinh; // ES6
Decimal.sqrt = sqrt;
Decimal.sub = sub;
Decimal.tan = tan;
Decimal.tanh = tanh; // ES6
Decimal.trunc = trunc; // ES6
if (obj === void 0) obj = {};
if (obj) {
ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
}
Decimal.config(obj);
return Decimal;
}
/*
* Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function div(x, y) {
return new this(x).div(y);
}
/*
* Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} The power to which to raise the base of the natural log.
*
*/
function exp(x) {
return new this(x).exp();
}
/*
* Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
*
* x {number|string|Decimal}
*
*/
function floor(x) {
return finalise(x = new this(x), x.e + 1, 3);
}
/*
* Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
* rounded to `precision` significant digits using rounding mode `rounding`.
*
* hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
*
*/
function hypot() {
var i, n,
t = new this(0);
external = false;
for (i = 0; i < arguments.length;) {
n = new this(arguments[i++]);
if (!n.d) {
if (n.s) {
external = true;
return new this(1 / 0);
}
t = n;
} else if (t.d) {
t = t.plus(n.times(n));
}
}
external = true;
return t.sqrt();
}
/*
* Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function ln(x) {
return new this(x).ln();
}
/*
* Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
* is specified, rounded to `precision` significant digits using rounding mode `rounding`.
*
* log[y](x)
*
* x {number|string|Decimal} The argument of the logarithm.
* y {number|string|Decimal} The base of the logarithm.
*
*/
function log(x, y) {
return new this(x).log(y);
}
/*
* Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function log2(x) {
return new this(x).log(2);
}
/*
* Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function log10(x) {
return new this(x).log(10);
}
/*
* Return a new Decimal whose value is the maximum of the arguments.
*
* arguments {number|string|Decimal}
*
*/
function max() {
return maxOrMin(this, arguments, 'lt');
}
/*
* Return a new Decimal whose value is the minimum of the arguments.
*
* arguments {number|string|Decimal}
*
*/
function min() {
return maxOrMin(this, arguments, 'gt');
}
/*
* Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function mod(x, y) {
return new this(x).mod(y);
}
/*
* Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function mul(x, y) {
return new this(x).mul(y);
}
/*
* Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} The base.
* y {number|string|Decimal} The exponent.
*
*/
function pow(x, y) {
return new this(x).pow(y);
}
/*
* Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
* `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
* are produced).
*
* [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
*
*/
function random(sd) {
var d, e, k, n,
i = 0,
r = new this(1),
rd = [];
if (sd === void 0) sd = this.precision;
else checkInt32(sd, 1, MAX_DIGITS);
k = Math.ceil(sd / LOG_BASE);
if (!this.crypto) {
for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
// Browsers supporting crypto.getRandomValues.
} else if (crypto.getRandomValues) {
d = crypto.getRandomValues(new Uint32Array(k));
for (; i < k;) {
n = d[i];
// 0 <= n < 4294967296
// Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
if (n >= 4.29e9) {
d[i] = crypto.getRandomValues(new Uint32Array(1))[0];
} else {
// 0 <= n <= 4289999999
// 0 <= (n % 1e7) <= 9999999
rd[i++] = n % 1e7;
}
}
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
d = crypto.randomBytes(k *= 4);
for (; i < k;) {
// 0 <= n < 2147483648
n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
// Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
if (n >= 2.14e9) {
crypto.randomBytes(4).copy(d, i);
} else {
// 0 <= n <= 2139999999
// 0 <= (n % 1e7) <= 9999999
rd.push(n % 1e7);
i += 4;
}
}
i = k / 4;
} else {
throw Error(cryptoUnavailable);
}
k = rd[--i];
sd %= LOG_BASE;
// Convert trailing digits to zeros according to sd.
if (k && sd) {
n = mathpow(10, LOG_BASE - sd);
rd[i] = (k / n | 0) * n;
}
// Remove trailing words which are zero.
for (; rd[i] === 0; i--) rd.pop();
// Zero?
if (i < 0) {
e = 0;
rd = [0];
} else {
e = -1;
// Remove leading words which are zero and adjust exponent accordingly.
for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
// Count the digits of the first word of rd to determine leading zeros.
for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
// Adjust the exponent for leading zeros of the first word of rd.
if (k < LOG_BASE) e -= LOG_BASE - k;
}
r.e = e;
r.d = rd;
return r;
}
/*
* Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
*
* To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
*
* x {number|string|Decimal}
*
*/
function round(x) {
return finalise(x = new this(x), x.e + 1, this.rounding);
}
/*
* Return
* 1 if x > 0,
* -1 if x < 0,
* 0 if x is 0,
* -0 if x is -0,
* NaN otherwise
*
*/
function sign(x) {
x = new this(x);
return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
}
/*
* Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function sin(x) {
return new this(x).sin();
}
/*
* Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function sinh(x) {
return new this(x).sinh();
}
/*
* Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function sqrt(x) {
return new this(x).sqrt();
}
/*
* Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function sub(x, y) {
return new this(x).sub(y);
}
/*
* Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function tan(x) {
return new this(x).tan();
}
/*
* Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function tanh(x) {
return new this(x).tanh();
}
/*
* Return a new Decimal whose value is `x` truncated to an integer.
*
* x {number|string|Decimal}
*
*/
function trunc(x) {
return finalise(x = new this(x), x.e + 1, 1);
}
// Create and configure initial Decimal constructor.
Decimal = clone(Decimal);
// Create the internal constants from their string values.
LN10 = new Decimal(LN10);
PI = new Decimal(PI);
// Export.
// AMD.
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return Decimal;
}.call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// Node and other environments that support module.exports.
} else if (typeof module != 'undefined' && module.exports) {
module.exports = Decimal['default'] = Decimal.Decimal = Decimal;
// Browser.
} else {
if (!globalScope) {
globalScope = typeof self != 'undefined' && self && self.self == self
? self : Function('return this')();
}
noConflict = globalScope.Decimal;
Decimal.noConflict = function () {
globalScope.Decimal = noConflict;
return Decimal;
};
globalScope.Decimal = Decimal;
}
})(this);
/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Messages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return checkForMessagesToSend; });
/* unused harmony export sendMessage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return showMessage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return loadMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initMessages; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Message; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__ = __webpack_require__(7);
/* Message.js */
function Message(filename="", msg="") {
this.filename = filename;
this.msg = msg;
this.recvd = false;
}
Message.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Message", this);
}
Message.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Message, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.Message = Message;
//Sends message to player, including a pop up
function sendMessage(msg) {
console.log("sending message: " + msg.filename);
msg.recvd = true;
if (!__WEBPACK_IMPORTED_MODULE_4__Settings_js__["a" /* Settings */].SuppressMessages) {
showMessage(msg);
}
addMessageToServer(msg, "home");
}
function showMessage(msg) {
var txt = "Message received from unknown sender: <br><br>" +
"<i>" + msg.msg + "</i><br><br>" +
"This message was saved as " + msg.filename + " onto your home computer.";
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);
}
//Adds a message to a server
function addMessageToServer(msg, serverHostname) {
var server = Object(__WEBPACK_IMPORTED_MODULE_3__Server_js__["c" /* GetServerByHostname */])(serverHostname);
if (server == null) {
console.log("WARNING: Did not locate " + serverHostname);
return;
}
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 jumper5 = Messages[MessageFilenames.Jumper5];
var cybersecTest = Messages[MessageFilenames.CyberSecTest];
var nitesecTest = Messages[MessageFilenames.NiteSecTest];
var bitrunnersTest = Messages[MessageFilenames.BitRunnersTest];
var redpill = Messages[MessageFilenames.RedPill];
var redpillOwned = false;
if (__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["b" /* AugmentationNames */].TheRedPill].owned) {
redpillOwned = true;
}
if (jumper0 && !jumper0.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 25) {
sendMessage(jumper0);
} else if (jumper1 && !jumper1.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 40) {
sendMessage(jumper1);
} else if (cybersecTest && !cybersecTest.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 50) {
sendMessage(cybersecTest);
} else if (jumper2 && !jumper2.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 175) {
sendMessage(jumper2);
} else if (nitesecTest && !nitesecTest.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 200) {
sendMessage(nitesecTest);
} else if (jumper3 && !jumper3.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 350) {
sendMessage(jumper3);
} else if (jumper4 && !jumper4.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 490) {
sendMessage(jumper4);
} else if (bitrunnersTest && !bitrunnersTest.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 500) {
sendMessage(bitrunnersTest);
} else if (jumper5 && !jumper5.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 1000) {
sendMessage(jumper5);
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_1__CreateProgram_js__["a" /* Programs */].Flight);
} else if (redpill && !redpill.recvd && __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill >= 2000 && redpillOwned) {
sendMessage(redpill);
}
}
function AddToAllMessages(msg) {
Messages[msg.filename] = msg;
}
let Messages = {}
function loadMessages(saveString) {
Messages = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */]);
}
let MessageFilenames = {
Jumper0: "j0.msg",
Jumper1: "j1.msg",
Jumper2: "j2.msg",
Jumper3: "j3.msg",
Jumper4: "j4.msg",
Jumper5: "j5.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. <br><br>It's real, I've seen it. And I can " +
"help you find it. But not right now. You're not ready yet.<br><br>-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. <br><br>" +
"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.<br><br>" +
"-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. <br><br>Watch out for a hacking group known as NiteSec." +
"<br><br>-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. <br><br>" +
"I.I.I.I <br><br>-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.<br><br>" +
"-jump3R"));
AddToAllMessages(new Message(MessageFilenames.Jumper5,
"Build your wings and fly<br><br>-jump3R<br><br> " +
"The fl1ght.exe program was added to your home computer"));
//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. <br><br>" +
"But first, you must pass our test. Find and hack our server using the Terminal. <br><br>" +
"-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. <br><br>" +
"Join us, and people will fear you, too. <br><br>" +
"Find and hack our hidden server using the Terminal. Then, we will contact you again." +
"<br><br>-NiteSec"));
AddToAllMessages(new Message(MessageFilenames.BitRunnersTest,
"We know what you are doing. We know what drives you. We know " +
"what you are looking for. <br><br> " +
"We can help you find the answers.<br><br>" +
"run4theh111z"));
AddToAllMessages(new Message(MessageFilenames.RedPill,
"@)(#V%*N)@(#*)*C)@#%*)*V)@#(*%V@)(#VN%*)@#(*%<br>" +
")@B(*#%)@)M#B*%V)____FIND___#$@)#%(B*)@#(*%B)<br>" +
"@_#(%_@#M(BDSPOMB__THE-CAVE_#)$(*@#$)@#BNBEGB<br>" +
"DFLSMFVMV)#@($*)@#*$MV)@#(*$V)M#(*$)M@(#*VM$)"));
}
/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StockMarket; });
/* unused harmony export StockSymbols */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return initStockSymbols; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return initSymbolToStockMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return stockMarketCycle; });
/* unused harmony export buyStock */
/* unused harmony export sellStock */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return updateStockPrices; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayStockMarketContent; });
/* unused harmony export updateStockTicker */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return updateStockPlayerPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return loadStockMarket; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return setStockMarketContentCreated; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* StockMarket.js */
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.mv = mv;
this.b = b;
this.otlkMag = otlkMag;
}
Stock.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Stock", this);
}
Stock.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Stock, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.Stock = Stock;
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, __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */]);
}
}
function initStockSymbols() {
//Stocks for companies at which you can work
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp] = "ECP";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp] = "MGCP";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries] = "BLD";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated] = "CLRK";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated] = "OMTK";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma] = "FSIG";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational] = "KGI";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies] = "FLCM";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies] = "STM";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm] = "DCOMM";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs] = "HLS";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife] = "VITA";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems] = "ICRS";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy] = "UNV";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp] = "AERO";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems] = "OMN";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems] = "SLRS";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals] = "GPH";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical] = "NVMD";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity] = "WDS";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp] = "LXO";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction] = "RHOC";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises] = "APHE";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities] = "SYSC";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek] = "CTK";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies] = "NTLK";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware] = "OMGA";
StockSymbols[__WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumECorp;
var ecorpStk = new Stock(ecorp, StockSymbols[ecorp], 0.5, true, 16, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000));
StockMarket[ecorp] = ecorpStk;
var megacorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12MegaCorp;
var megacorpStk = new Stock(megacorp, StockSymbols[megacorp], 0.5, true, 16, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(25000, 33000));
StockMarket[megacorp] = megacorpStk;
var blade = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12BladeIndustries;
var bladeStk = new Stock(blade, StockSymbols[blade], 0.75, true, 13, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 22000));
StockMarket[blade] = bladeStk;
var clarke = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumClarkeIncorporated;
var clarkeStk = new Stock(clarke, StockSymbols[clarke], 0.7, true, 12, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000));
StockMarket[clarke] = clarkeStk;
var omnitek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniTekIncorporated;
var omnitekStk = new Stock(omnitek, StockSymbols[omnitek], 0.65, true, 12, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(35000, 40000));
StockMarket[omnitek] = omnitekStk;
var foursigma = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FourSigma;
var foursigmaStk = new Stock(foursigma, StockSymbols[foursigma], 1.1, true, 18, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(60000, 70000));
StockMarket[foursigma] = foursigmaStk;
var kuaigong = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingKuaiGongInternational;
var kuaigongStk = new Stock(kuaigong, StockSymbols[kuaigong], 0.8, true, 10, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 24000));
StockMarket[kuaigong] = kuaigongStk;
var fulcrum = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumFulcrumTechnologies;
var fulcrumStk = new Stock(fulcrum, StockSymbols[fulcrum], 1.25, true, 17, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(30000, 35000));
StockMarket[fulcrum] = fulcrumStk;
var storm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaStormTechnologies;
var stormStk = new Stock(storm, StockSymbols[storm], 0.85, true, 7, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(21000, 24000));
StockMarket[storm] = stormStk;
var defcomm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoDefComm;
var defcommStk = new Stock(defcomm, StockSymbols[defcomm], 0.65, true, 10, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000));
StockMarket[defcomm] = defcommStk;
var helios = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenHeliosLabs;
var heliosStk = new Stock(helios, StockSymbols[helios], 0.6, true, 9, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(12000, 16000));
StockMarket[helios] = heliosStk;
var vitalife = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoVitaLife;
var vitalifeStk = new Stock(vitalife, StockSymbols[vitalife], 0.75, true, 7, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 12000));
StockMarket[vitalife] = vitalifeStk;
var icarus = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12IcarusMicrosystems;
var icarusStk = new Stock(icarus, StockSymbols[icarus], 0.65, true, 7.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(16000, 20000));
StockMarket[icarus] = icarusStk;
var universalenergy = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12UniversalEnergy;
var universalenergyStk = new Stock(universalenergy, StockSymbols[universalenergy], 0.55, true, 10, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000));
StockMarket[universalenergy] = universalenergyStk;
var aerocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumAeroCorp;
var aerocorpStk = new Stock(aerocorp, StockSymbols[aerocorp], 0.6, true, 6, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(10000, 15000));
StockMarket[aerocorp] = aerocorpStk;
var omnia = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenOmniaCybersystems;
var omniaStk = new Stock(omnia, StockSymbols[omnia], 0.7, true, 4.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(9000, 12000));
StockMarket[omnia] = omniaStk;
var solaris = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].ChongqingSolarisSpaceSystems;
var solarisStk = new Stock(solaris, StockSymbols[solaris], 0.75, true, 8.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000));
StockMarket[solaris] = solarisStk;
var globalpharm = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].NewTokyoGlobalPharmaceuticals;
var globalpharmStk = new Stock(globalpharm, StockSymbols[globalpharm], 0.6, true, 10.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000));
StockMarket[globalpharm] = globalpharmStk;
var nova = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaNovaMedical;
var novaStk = new Stock(nova, StockSymbols[nova], 0.75, true, 5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(18000, 24000));
StockMarket[nova] = novaStk;
var watchdog = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumWatchdogSecurity;
var watchdogStk = new Stock(watchdog, StockSymbols[watchdog], 1, true, 1.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500));
StockMarket[watchdog] = watchdogStk;
var lexocorp = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenLexoCorp;
var lexocorpStk = new Stock(lexocorp, StockSymbols[lexocorp], 1.25, true, 3, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500));
StockMarket[lexocorp] = lexocorpStk;
var rho = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumRhoConstruction;
var rhoStk = new Stock(rho, StockSymbols[rho], 0.6, true, 1, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000));
StockMarket[rho] = rhoStk;
var alpha = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12AlphaEnterprises;
var alphaStk = new Stock(alpha, StockSymbols[alpha], 1.05, true, 2, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(5000, 7500));
StockMarket[alpha] = alphaStk;
var syscore = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenSysCoreSecurities;
var syscoreStk = new Stock(syscore, StockSymbols[syscore], 1.25, true, 0, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(4000, 7000))
StockMarket[syscore] = syscoreStk;
var computek = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].VolhavenCompuTek;
var computekStk = new Stock(computek, StockSymbols[computek], 0.9, true, 0, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 5000));
StockMarket[computek] = computekStk;
var netlink = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].AevumNetLinkTechnologies;
var netlinkStk = new Stock(netlink, StockSymbols[netlink], 1, true, 1, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 4000));
StockMarket[netlink] = netlinkStk;
var omega = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].IshimaOmegaSoftware;
var omegaStk = new Stock(omega, StockSymbols[omega], 1, true, 0.5, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(3000, 6000));
StockMarket[omega] = omegaStk;
var fns = __WEBPACK_IMPORTED_MODULE_2__Location_js__["a" /* Locations */].Sector12FoodNStuff;
var fnsStk = new Stock(fns, StockSymbols[fns], 0.75, false, 1, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 4000));
StockMarket[fns] = fnsStk;
var sigmacosm = "Sigma Cosmetics";
var sigmacosmStk = new Stock(sigmacosm, StockSymbols[sigmacosm], 0.9, true, 0, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(2000, 3000));
StockMarket[sigmacosm] = sigmacosmStk;
var joesguns = "Joes Guns";
var joesgunsStk = new Stock(joesguns, StockSymbols[joesguns], 1, true, 1, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(500, 1000));
StockMarket[joesguns] = joesgunsStk;
var catalyst = "Catalyst Ventures";
var catalystStk = new Stock(catalyst, StockSymbols[catalyst], 1.25, true, 0, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(1000, 1500));
StockMarket[catalyst] = catalystStk;
var microdyne = "Microdyne Technologies";
var microdyneStk = new Stock(microdyne, StockSymbols[microdyne], 0.75, true, 8, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(20000, 25000));
StockMarket[microdyne] = microdyneStk;
var titanlabs = "Titan Laboratories";
var titanlabsStk = new Stock(titanlabs, StockSymbols[titanlabs], 0.6, true, 11, Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["d" /* getRandomInt */])(15000, 20000));
StockMarket[titanlabs] = titanlabsStk;
}
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() {
console.log("Cycling the Stock Market");
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
var thresh = 0.62;
if (stock.b) {thresh = 0.38;}
if (Math.random() < thresh) {
stock.b = !stock.b;
}
}
}
}
//Returns true if successful, false otherwise
function buyStock(stock, shares) {
if (shares == 0) {return false;}
if (stock == null || shares < 0 || isNaN(shares)) {
Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to buy stock. This may be a bug, contact developer");
return false;
}
shares = Math.round(shares);
var totalPrice = stock.price * shares;
if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) {
Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this. You need $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString() + ".");
return false;
}
var origTotal = stock.playerShares * stock.playerAvgPx;
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission);
var newTotal = origTotal + totalPrice;
stock.playerShares += shares;
stock.playerAvgPx = newTotal / stock.playerShares;
updateStockPlayerPosition(stock);
Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Bought " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. You also paid $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Failed to sell stock. This may be a bug, contact developer");
return false;
}
if (shares > stock.playerShares) {shares = stock.playerShares;}
if (shares == 0) {return false;}
var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission;
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].gainMoney(gains);
stock.playerShares -= shares;
if (stock.playerShares == 0) {
stock.playerAvgPx = 0;
}
updateStockPlayerPosition(stock);
Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Sold " + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. After commissions, you gained " +
"a total of $" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2));
return true;
}
function updateStockPrices() {
var v = Math.random();
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
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;}
}
var c = Math.random();
if (c < chc) {
stock.price *= (1 + av);
if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.StockMarket) {
updateStockTicker(stock, true);
}
} else {
stock.price /= (1 + av);
if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["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;
}
}
}
}
function setStockMarketContentCreated(b) {
stockMarketContentCreated = b;
}
var stockMarketContentCreated = false;
function displayStockMarketContent() {
if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount == null) {__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount = false;}
if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasTixApiAccess == null) {__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasTixApiAccess = false;}
//Purchase WSE Account button
var wseAccountButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-account");
wseAccountButton.innerText = "Buy WSE Account - $" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost, 2).toString();
if (!__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount && __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost)) {
wseAccountButton.setAttribute("class", "a-link-button");
} else {
wseAccountButton.setAttribute("class", "a-link-button-inactive");
}
wseAccountButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount = true;
initStockMarket();
initSymbolToStockMap();
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].WSEAccountCost);
displayStockMarketContent();
return false;
});
//Purchase TIX API Access account
var tixApiAccessButton = Object(__WEBPACK_IMPORTED_MODULE_5__utils_HelperFunctions_js__["b" /* clearEventListeners */])("stock-market-buy-tix-api");
tixApiAccessButton.innerText = "Buy Trade Information eXchange (TIX) API Access - $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost, 2).toString();
if (!__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasTixApiAccess && __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].money.gte(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost)) {
tixApiAccessButton.setAttribute("class", "a-link-button");
} else {
tixApiAccessButton.setAttribute("class", "a-link-button-inactive");
}
tixApiAccessButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasTixApiAccess = true;
__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].TIXAPICost);
displayStockMarketContent();
return false;
});
var stockList = document.getElementById("stock-market-list");
if (stockList == null) {return;}
if (!__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount) {
stockMarketContentCreated = false;
while (stockList.firstChild) {
stockList.removeChild(stockList.firstChild);
}
return;
}
if (!stockMarketContentCreated && __WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount) {
console.log("Creating Stock Market UI");
document.getElementById("stock-market-commission").innerHTML =
"Commission Fees: Every transaction you make has a $" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2) + " commission fee.<br><br>" +
"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 hdrLi = document.createElement("li");
var hdrName = document.createElement("p");
var hdrSym = document.createElement("p");
var hdrPrice = document.createElement("p");
var hdrQty = document.createElement("p");
var hdrBuySell = document.createElement("p")
var hdrAvgPrice = document.createElement("p");
var hdrShares = document.createElement("p");
var hdrReturn = document.createElement("p");
hdrName.style.display = "inline-block";
hdrName.innerText = "Stock Name";
hdrName.style.width = "8%";
hdrSym.style.display = "inline-block";
hdrSym.innerText = "Symbol";
hdrSym.style.width = "4%";
hdrPrice.style.display = "inline-block";
hdrPrice.innerText = "Price";
hdrPrice.style.width = "8%";
hdrQty.style.display = "inline-block";
hdrQty.innerText = "Quantity";
hdrQty.style.width = "3%";
hdrBuySell.style.display = "inline-block";
hdrBuySell.innerText = "Buy/Sell";
hdrBuySell.style.width = "5%";
hdrAvgPrice.style.display = "inline-block";
hdrAvgPrice.innerText = "Avg price of owned shares";
hdrAvgPrice.style.width = "7.5%";
hdrShares.style.display = "inline-block";
hdrShares.innerText = "Shares owned";
hdrShares.style.width = "4%";
hdrReturn.style.display = "inline-block";
hdrReturn.innerText = "Total Return";
hdrReturn.style.width = "6%";
hdrLi.appendChild(hdrName);
hdrLi.appendChild(hdrSym);
hdrLi.appendChild(hdrPrice);
hdrLi.appendChild(hdrQty);
hdrLi.appendChild(hdrBuySell);
hdrLi.appendChild(hdrAvgPrice);
hdrLi.appendChild(hdrShares);
hdrLi.appendChild(hdrReturn);
stockList.appendChild(hdrLi);
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
(function() {
var stock = StockMarket[name];
var li = document.createElement("li");
var stkName = document.createElement("p");
var stkSym = document.createElement("p");
var stkPrice = document.createElement("p");
var qtyInput = document.createElement("input");
var buyButton = document.createElement("span");
var sellButton = document.createElement("span");
var avgPriceTxt = document.createElement("p");
var sharesTxt = document.createElement("p");
var returnTxt = document.createElement("p");
var tickerId = "stock-market-ticker-" + stock.symbol;
stkName.setAttribute("id", tickerId + "-name");
stkSym.setAttribute("id", tickerId + "-sym");
stkPrice.setAttribute("id", tickerId + "-price");
stkName.style.display = "inline-block";
stkName.style.width = "8%";
stkSym.style.display = "inline-block";
stkSym.style.width = "4%";
stkPrice.style.display = "inline-block";
stkPrice.style.width = "9%";
li.setAttribute("display", "inline-block");
qtyInput.setAttribute("type", "text");
qtyInput.setAttribute("id", tickerId + "-qty-input");
qtyInput.setAttribute("class", "stock-market-qty-input");
qtyInput.setAttribute("onkeydown", "return ( event.ctrlKey || event.altKey " +
" || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) " +
" || (95<event.keyCode && event.keyCode<106) " +
" || (event.keyCode==8) || (event.keyCode==9) " +
" || (event.keyCode>34 && event.keyCode<40) " +
" || (event.keyCode==46) )");
qtyInput.style.width = "3%";
qtyInput.style.display = "inline-block";
buyButton.innerHTML = "Buy";
buyButton.setAttribute("class", "stock-market-buy-sell-button");
buyButton.style.width = "3%";
buyButton.style.display = "inline-block";
buyButton.addEventListener("click", function() {
var shares = document.getElementById(tickerId + "-qty-input").value;
shares = Number(shares);
if (isNaN(shares)) {return false;}
buyStock(stock, shares);
});
sellButton.innerHTML = "Sell";
sellButton.setAttribute("class", "stock-market-buy-sell-button");
sellButton.style.width = "3%";
sellButton.style.display = "inline-block";
sellButton.addEventListener("click", function() {
var shares = document.getElementById(tickerId + "-qty-input").value;
shares = Number(shares);
if (isNaN(shares)) {return false;}
sellStock(stock, shares);
});
avgPriceTxt.setAttribute("id", tickerId + "-avgprice");
avgPriceTxt.style.display = "inline-block";
avgPriceTxt.style.width = "8%";
avgPriceTxt.style.color = "white";
sharesTxt.setAttribute("id", tickerId + "-shares");
sharesTxt.style.display = "inline-block";
sharesTxt.style.width = "4%";
sharesTxt.style.color = "white";
returnTxt.setAttribute("id", tickerId + "-return");
returnTxt.style.display = "inline-block";
returnTxt.style.width = "6%";
returnTxt.style.color = "white";
li.appendChild(stkName);
li.appendChild(stkSym);
li.appendChild(stkPrice);
li.appendChild(qtyInput);
li.appendChild(buyButton);
li.appendChild(sellButton);
li.appendChild(avgPriceTxt);
li.appendChild(sharesTxt);
li.appendChild(returnTxt);
stockList.appendChild(li);
}()); //Immediate invocation
}//End if
}
stockMarketContentCreated = true;
}
if (__WEBPACK_IMPORTED_MODULE_3__Player_js__["a" /* Player */].hasWseAccount) {
for (var name in StockMarket) {
if (StockMarket.hasOwnProperty(name)) {
var stock = StockMarket[name];
updateStockTicker(stock, true);
updateStockPlayerPosition(stock);
}
}
}
}
//'increase' argument is a boolean indicating whether the price increased or decreased
function updateStockTicker(stock, increase) {
var tickerId = "stock-market-ticker-" + stock.symbol;
let stkName = document.getElementById(tickerId + "-name");
let stkSym = document.getElementById(tickerId + "-sym");
let stkPrice = document.getElementById(tickerId + "-price");
if (stkName == null || stkSym == null || stkPrice == null) {
console.log("ERROR, couldn't find elements with tickerId " + tickerId);
return;
}
stkName.innerText = stock.name;
stkSym.innerText = stock.symbol;
stkPrice.innerText = "$" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2).toString();
var returnTxt = document.getElementById(tickerId + "-return");
var totalCost = stock.playerShares * stock.playerAvgPx;
var gains = (stock.price - stock.playerAvgPx) * stock.playerShares;
var percentageGains = gains / totalCost;
if (totalCost > 0) {
returnTxt.innerText = "$" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2) + " (" +
Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(percentageGains * 100, 2) + "%)";
} else {
returnTxt.innerText = "N/A";
}
if (increase) {
stkName.style.color = "#66ff33";
stkSym.style.color = "#66ff33";
stkPrice.style.color = "#66ff33";
} else {
stkName.style.color = "red";
stkSym.style.color = "red";
stkPrice.style.color = "red";
}
}
function updateStockPlayerPosition(stock) {
var tickerId = "stock-market-ticker-" + stock.symbol;
var avgPriceTxt = document.getElementById(tickerId + "-avgprice");
var sharesTxt = document.getElementById(tickerId + "-shares");
if (avgPriceTxt == null || sharesTxt == null) {
Object(__WEBPACK_IMPORTED_MODULE_4__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Could not find element for player positions for stock " +
stock.symbol + ". This is a bug please contact developer");
return;
}
avgPriceTxt.innerText = "$" + Object(__WEBPACK_IMPORTED_MODULE_7__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.playerAvgPx, 2);
sharesTxt.innerText = stock.playerShares.toString();
}
/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return logBoxCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return logBoxUpdateText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return logBoxOpened; });
/* unused harmony export logBoxCurrentScript */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__ = __webpack_require__(1);
$(document).keydown(function(event) {
if (logBoxOpened && event.keyCode == 27) {
logBoxClose();
}
});
function logBoxInit() {
var closeButton = document.getElementById("log-box-close");
logBoxClose();
//Close Dialog box
closeButton.addEventListener("click", function() {
logBoxClose();
return false;
});
};
document.addEventListener("DOMContentLoaded", logBoxInit, false);
function logBoxClose() {
logBoxOpened = false;
var logBox = document.getElementById("log-box-container");
logBox.style.display = "none";
}
function logBoxOpen() {
logBoxOpened = true;
var logBox = document.getElementById("log-box-container");
logBox.style.display = "block";
}
var logBoxOpened = false;
var logBoxCurrentScript = null;
//ram argument is in GB
function logBoxCreate(script) {
logBoxCurrentScript = script;
logBoxOpen();
logBoxUpdateText();
}
function logBoxUpdateText() {
var txt = document.getElementById("log-box-text");
if (logBoxCurrentScript && logBoxOpened && txt) {
txt.innerHTML = logBoxCurrentScript.filename + Object(__WEBPACK_IMPORTED_MODULE_0__HelperFunctions_js__["f" /* printArray */])(logBoxCurrentScript.args) + ":<br><br>";
for (var i = 0; i < logBoxCurrentScript.logs.length; ++i) {
txt.innerHTML += logBoxCurrentScript.logs[i];
txt.innerHTML += "<br>";
}
}
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return setActiveScriptsClickHandlers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addActiveScriptsItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deleteActiveScriptsItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return updateActiveScriptsItems; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_LogBox_js__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* Active Scripts UI*/
function setActiveScriptsClickHandlers() {
//Server panel click handlers
var serverPanels = document.getElementsByClassName("active-scripts-server-header");
if (serverPanels == null) {
console.log("ERROR: Could not find Active Scripts server panels");
return;
}
for (i = 0; i < serverPanels.length; ++i) {
serverPanels[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
//Script Panel click handlers
var scriptPanels = document.getElementsByClassName("active-scripts-script-header");
if (scriptPanels == null) {
console.log("ERROR: Could not find Active Scripts panels for individual scripts");
return;
}
for (var i = 0; i < scriptPanels.length; ++i) {
scriptPanels[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
}
//Returns the ul element containins all script items for a specific server
function getActiveScriptsServerList(server) {
if (server == null) {return null;}
var panelname = "active-scripts-server-panel-" + server.hostname;
var item = document.getElementById(panelname + "-script-list");
if (item == null) {
console.log("ERROR: Cannot find list for: " + server.hostname);
}
return item;
}
function createActiveScriptsServerPanel(server) {
var panelname = "active-scripts-server-panel-" + server.hostname;
var activeScriptsList = document.getElementById("active-scripts-list");
//Div of entire Panel
var panelDiv = document.createElement("div");
panelDiv.setAttribute("id", panelname);
//Panel Header
var panelHdr = document.createElement("button");
panelHdr.setAttribute("class", "active-scripts-server-header")
panelHdr.setAttribute("id", panelname + "-hdr");
panelHdr.innerHTML = server.hostname;
//Panel content
var panelContentDiv = document.createElement("div");
panelContentDiv.setAttribute("class", "active-scripts-server-panel");
panelContentDiv.setAttribute("id", panelname + "-content");
//List of scripts
var panelScriptList = document.createElement("ul");
panelScriptList.setAttribute("id", panelname + "-script-list");
panelContentDiv.appendChild(panelScriptList);
panelDiv.appendChild(panelHdr);
panelDiv.appendChild(panelContentDiv);
activeScriptsList.appendChild(panelDiv);
setActiveScriptsClickHandlers() //Reset click handlers
return panelDiv;
}
//Deletes the info for a particular server (Dropdown header + Panel with all info)
//in the Active Scripts page if it exists
function deleteActiveScriptsServerPanel(server) {
var panelname = "active-scripts-server-panel-" + server.hostname;
var panel = document.getElementById(panelname);
if (panel == null) {
console.log("No such panel exists: " + panelname);
return;
}
//Remove the panel if it has no elements
var scriptList = document.getElementById(panelname + "-script-list");
if (scriptList.childNodes.length == 0) {
panel.parentNode.removeChild(panel);
}
}
function addActiveScriptsItem(workerscript) {
//Get server panel
var server = Object(__WEBPACK_IMPORTED_MODULE_1__Server_js__["e" /* getServer */])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript.");
return;
}
var panelname = "active-scripts-server-panel-" + server.hostname;
var panel = document.getElementById(panelname);
if (panel == null) {
panel = createActiveScriptsServerPanel(server);
}
//Create the element itself. Each element is an accordion collapsible
var itemNameArray = ["active", "scripts", server.hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(workerscript.args[i].toString());
}
var itemName = itemNameArray.join("-");
//var itemName = "active-scripts-" + server.hostname + "-" + workerscript.name;
var item = document.createElement("li");
item.setAttribute("id", itemName);
var btn = document.createElement("button");
btn.setAttribute("class", "active-scripts-script-header");
btn.innerHTML = workerscript.name;
var itemContentDiv = document.createElement("div");
itemContentDiv.setAttribute("class", "active-scripts-script-panel");
itemContentDiv.setAttribute("id", itemName + "-content");
item.appendChild(btn);
item.appendChild(itemContentDiv);
createActiveScriptsText(workerscript, itemContentDiv);
//Append element to list
var list = getActiveScriptsServerList(server);
list.appendChild(item);
setActiveScriptsClickHandlers() //Reset click handlers
}
function deleteActiveScriptsItem(workerscript) {
var server = Object(__WEBPACK_IMPORTED_MODULE_1__Server_js__["e" /* getServer */])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript.");
return;
}
var itemNameArray = ["active", "scripts", server.hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(workerscript.args[i].toString());
}
var itemName = itemNameArray.join("-");
//var itemName = "active-scripts-" + server.hostname + "-" + workerscript.name;
var li = document.getElementById(itemName);
if (li == null) {
console.log("could not find Active scripts li element for: " + workerscript.name);
return;
}
li.parentNode.removeChild(li);
deleteActiveScriptsServerPanel(server);
}
//Update the ActiveScriptsItems array
function updateActiveScriptsItems() {
var total = 0;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__["h" /* workerScripts */].length; ++i) {
total += updateActiveScriptsItemContent(__WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__["h" /* workerScripts */][i]);
}
document.getElementById("active-scripts-total-prod").innerHTML =
"Total online production rate: $" + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(total, 2) + " / second";
}
//Updates the content of the given item in the Active Scripts list
function updateActiveScriptsItemContent(workerscript) {
var server = Object(__WEBPACK_IMPORTED_MODULE_1__Server_js__["e" /* getServer */])(workerscript.serverIp);
if (server == null) {
console.log("ERROR: Invalid server IP for workerscript.");
return;
}
var itemNameArray = ["active", "scripts", server.hostname, workerscript.name];
for (var i = 0; i < workerscript.args.length; ++i) {
itemNameArray.push(workerscript.args[i].toString());
}
var itemName = itemNameArray.join("-");
//var itemName = "active-scripts-" + server.hostname + "-" + workerscript.name;
var itemContent = document.getElementById(itemName + "-content")
//Clear the item
while (itemContent.firstChild) {
itemContent.removeChild(itemContent.firstChild);
}
//Add the updated text back. Returns the total online production rate
return createActiveScriptsText(workerscript, itemContent);
}
function createActiveScriptsText(workerscript, item) {
var itemText = document.createElement("p");
//Server ip/hostname
var threads = "Threads: " + workerscript.scriptRef.threads;
var args = "Args: " + Object(__WEBPACK_IMPORTED_MODULE_3__utils_HelperFunctions_js__["f" /* printArray */])(workerscript.args);
//Online
var onlineTotalMoneyMade = "Total online production: $" + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(workerscript.scriptRef.onlineMoneyMade, 2);
var onlineTotalExpEarned = (Array(26).join(" ") + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(workerscript.scriptRef.onlineExpGained, 2) + " hacking exp").replace( / /g, "&nbsp;");
var onlineMps = workerscript.scriptRef.onlineMoneyMade / workerscript.scriptRef.onlineRunningTime;
var onlineMpsText = "Online production rate: $" + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(onlineMps, 2) + "/second";
var onlineEps = workerscript.scriptRef.onlineExpGained / workerscript.scriptRef.onlineRunningTime;
var onlineEpsText = (Array(25).join(" ") + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(onlineEps, 4) + " hacking exp/second").replace( / /g, "&nbsp;");
//Offline
var offlineTotalMoneyMade = "Total offline production: $" + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(workerscript.scriptRef.offlineMoneyMade, 2);
var offlineTotalExpEarned = (Array(27).join(" ") + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(workerscript.scriptRef.offlineExpGained, 2) + " hacking exp").replace( / /g, "&nbsp;");
var offlineMps = workerscript.scriptRef.offlineMoneyMade / workerscript.scriptRef.offlineRunningTime;
var offlineMpsText = "Offline production rate: $" + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineMps, 2) + "/second";
var offlineEps = workerscript.scriptRef.offlineExpGained / workerscript.scriptRef.offlineRunningTime;
var offlineEpsText = (Array(26).join(" ") + Object(__WEBPACK_IMPORTED_MODULE_5__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineEps, 4) + " hacking exp/second").replace( / /g, "&nbsp;");
itemText.innerHTML = threads + "<br>" + args + "<br>" + onlineTotalMoneyMade + "<br>" + onlineTotalExpEarned + "<br>" +
onlineMpsText + "<br>" + onlineEpsText + "<br>" + offlineTotalMoneyMade + "<br>" + offlineTotalExpEarned + "<br>" +
offlineMpsText + "<br>" + offlineEpsText + "<br>";
item.appendChild(itemText);
var logButton = document.createElement("span");
logButton.innerHTML = "Log";
var killButton = document.createElement("span");
killButton.innerHTML = "Kill script";
logButton.setAttribute("class", "active-scripts-button");
killButton.setAttribute("class", "active-scripts-button");
logButton.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_4__utils_LogBox_js__["a" /* logBoxCreate */])(workerscript.scriptRef);
return false;
});
killButton.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_0__NetscriptWorker_js__["d" /* killWorkerScript */])(workerscript.scriptRef, workerscript.scriptRef.scriptRef.server);
Object(__WEBPACK_IMPORTED_MODULE_2__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Killing script, may take a few minutes to complete...");
return false;
});
item.appendChild(logButton);
item.appendChild(killButton);
//Return total online production rate
return onlineMps;
}
/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Environment; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__ = __webpack_require__(39);
/* Environment
* NetScript program environment
*/
function Environment(workerScript,parent) {
if (parent){
this.vars = parent.vars;
} else {
this.vars = Object(__WEBPACK_IMPORTED_MODULE_0__NetscriptFunctions_js__["a" /* NetscriptFunctions */])(workerScript);
}
this.parent = parent;
this.stopFlag = false;
}
Environment.prototype = {
//Create a "subscope", which is a new new "sub-environment"
//The subscope is linked to this through its parent variable
extend: function() {
return new Environment(this);
},
//Finds the scope where the variable with the given name is defined
lookup: function(name) {
var scope = this;
while (scope) {
if (Object.prototype.hasOwnProperty.call(scope.vars, name))
return scope;
scope = scope.parent;
}
},
//Get the current value of a variable
get: function(name) {
if (name in this.vars) {
return this.vars[name];
}
throw new Error("Undefined variable " + name);
},
//Sets the value of a variable in any scope
set: function(name, value) {
var scope = this.lookup(name);
// let's not allow defining globals from a nested environment
//
// If scope is null (aka existing variable with name could not be found)
// and this is NOT the global scope, throw error
if (!scope && this.parent) {
console.log("Here");
throw new Error("Undefined variable " + name);
}
return (scope || this).vars[name] = value;
},
setArrayElement: function(name, idx, value) {
var scope = this.lookup(name);
if (!scope && this.parent) {
console.log("Here");
throw new Error("Undefined variable " + name);
}
var arr = (scope || this).vars[name];
if (!(arr.constructor === Array || arr instanceof Array)) {
throw new Error("Variable is not an array: " + name);
}
return (scope || this).vars[name][idx] = value;
},
//Creates (or overwrites) a variable in the current scope
def: function(name, value) {
return this.vars[name] = value;
}
};
/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Gang; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return displayGangContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return updateGangContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadAllGangs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllGangs; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js__ = __webpack_require__(38);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__ = __webpack_require__(20);
/* Gang.js */
//Switch between territory and management screen with 1 and 2
$(document).keydown(function(event) {
if (__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].Page.Gang && !__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["e" /* yesNoBoxOpen */]) {
if (event.keyCode === 49) {
if(document.getElementById("gang-territory-subpage").style.display === "block") {
document.getElementById("gang-management-subpage-button").click();
}
} else if (event.keyCode === 50) {
if (document.getElementById("gang-management-subpage").style.display === "block") {
document.getElementById("gang-territory-subpage-button").click();
}
}
}
});
//Delete upgrade box when clicking outside
$(document).mousedown(function(event) {
if (gangMemberUpgradeBoxOpened) {
if ( $(event.target).closest("#gang-purchase-upgrade-container").get(0) == null ) {
//Delete the box
var container = document.getElementById("gang-purchase-upgrade-container");
while(container.firstChild) {
container.removeChild(container.firstChild);
}
container.parentNode.removeChild(container);
gangMemberUpgradeBoxOpened = false;
}
}
});
let GangNames = ["Slum Snakes", "Tetrads", "The Syndicate", "The Dark Army", "Speakers for the Dead",
"NiteSec", "The Black Hand"];
let GangLocations = [__WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].Aevum, __WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].Chongqing, __WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].Sector12, __WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].NewTokyo,
__WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].Ishima, __WEBPACK_IMPORTED_MODULE_3__Location_js__["a" /* Locations */].Volhaven];
let AllGangs = {
"Slum Snakes" : {
power: 1,
territory: 1/7,
},
"Tetrads" : {
power: 1,
territory: 1/7,
},
"The Syndicate" : {
power: 1,
territory: 1/7,
},
"The Dark Army" : {
power: 1,
territory: 1/7,
},
"Speakers for the Dead" : {
power: 1,
territory: 1/7,
},
"NiteSec" : {
power: 1,
territory: 1/7,
},
"The Black Hand" : {
power: 1,
territory: 1/7,
},
}
function loadAllGangs(saveString) {
AllGangs = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */]);
}
//Power is an estimate of a gang's ability to gain/defend territory
let gangStoredPowerCycles = 0;
function processAllGangPowerGains(numCycles=1) {
if (!__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].inGang()) {return;}
gangStoredPowerCycles += numCycles;
if (gangStoredPowerCycles < 150) {return;}
var playerGangName = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName;
for (var name in AllGangs) {
if (AllGangs.hasOwnProperty(name)) {
if (name == playerGangName) {
AllGangs[name].power += __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.calculatePower();
} else {
var gain = Math.random() * 0.01; //TODO Adjust as necessary
AllGangs[name].power += (gain);
}
}
}
gangStoredPowerCycles -= 150;
}
let gangStoredTerritoryCycles = 0;
function processAllGangTerritory(numCycles=1) {
if (!__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].inGang()) {return;}
gangStoredTerritoryCycles += numCycles;
if (gangStoredTerritoryCycles < __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].GangTerritoryUpdateTimer) {return;}
for (var i = 0; i < GangNames.length; ++i) {
var other = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(0, GangNames.length-1);
while(other == i) {
other = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["d" /* getRandomInt */])(0, GangNames.length-1);
}
var thisPwr = AllGangs[GangNames[i]].power;
var otherPwr = AllGangs[GangNames[other]].power;
var thisChance = thisPwr / (thisPwr + otherPwr);
if (Math.random() < thisChance) {
if (AllGangs[GangNames[other]].territory <= 0) {
return;
}
AllGangs[GangNames[i]].territory += 0.0001;
AllGangs[GangNames[other]].territory -= 0.0001;
} else {
if (AllGangs[GangNames[i]].territory <= 0) {
return;
}
AllGangs[GangNames[i]].territory -= 0.0001;
AllGangs[GangNames[other]].territory += 0.0001;
}
}
gangStoredTerritoryCycles -= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].GangTerritoryUpdateTimer;
}
/* faction - Name of corresponding faction
hacking - Boolean indicating whether its a hacking gang or not
*/
function Gang(facName, hacking=false) {
this.facName = facName;
this.members = []; //Array of GangMembers
this.wanted = 1;
this.respect = 1;
this.power = 0;
this.isHackingGang = hacking;
this.respectGainRate = 0;
this.wantedGainRate = 0;
this.moneyGainRate = 0;
//When processing gains, this stores the number of cycles until some
//limit is reached, and then calculates and applies the gains only at that limit
this.storedCycles = 0;
}
Gang.prototype.process = function(numCycles=1) {
this.processGains(numCycles);
this.processExperienceGains(numCycles);
processAllGangPowerGains(numCycles);
processAllGangTerritory(numCycles);
}
Gang.prototype.processGains = function(numCycles=1) {
this.storedCycles += numCycles;
if (isNaN(this.storedCycles)) {
console.log("ERROR: Gang's storedCylces is NaN");
this.storedCycles = 0;
}
if (this.storedCycles < 25) {return;} //Only process every 5 seconds at least
//Get gains per cycle
var moneyGains = 0, respectGains = 0, wantedLevelGains = 0;
for (var i = 0; i < this.members.length; ++i) {
respectGains += (this.members[i].calculateRespectGain());
wantedLevelGains += (this.members[i].calculateWantedLevelGain());
moneyGains += (this.members[i].calculateMoneyGain());
}
this.respectGainRate = respectGains;
this.wantedGainRate = wantedLevelGains;
this.moneyGainRate = moneyGains;
if (!isNaN(respectGains)) {
var gain = respectGains * this.storedCycles;
this.respect += (gain);
//Faction reputation gains is respect gain divided by some constant
var fac = __WEBPACK_IMPORTED_MODULE_2__Faction_js__["b" /* Factions */][this.facName];
if (!(fac instanceof __WEBPACK_IMPORTED_MODULE_2__Faction_js__["a" /* Faction */])) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERROR: Could not get Faction associates with your gang. This is a bug, please report to game dev");
} else {
var favorMult = 1 + (fac.favor / 100);
fac.playerReputation += ((__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].faction_rep_mult * gain * favorMult) / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].GangRespectToReputationRatio);
}
} else {
console.log("ERROR: respectGains is NaN");
}
if (!isNaN(wantedLevelGains)) {
this.wanted += (wantedLevelGains * this.storedCycles);
if (this.wanted < 1) {this.wanted = 1;}
} else {
console.log("ERROR: wantedLevelGains is NaN");
}
if (!isNaN(moneyGains)) {
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gainMoney(moneyGains * this.storedCycles);
} else {
console.log("ERROR: respectGains is NaN");
}
this.storedCycles = 0;
}
Gang.prototype.processExperienceGains = function(numCycles=1) {
for (var i = 0; i < this.members.length; ++i) {
this.members[i].gainExperience(numCycles);
this.members[i].updateSkillLevels();
}
}
//Calculates power GAIN, which is added onto the Gang's existing power
Gang.prototype.calculatePower = function() {
var memberTotal = 0;
for (var i = 0; i < this.members.length; ++i) {
if (this.members[i].task instanceof GangMemberTask &&
this.members[i].task.name == "Territory Warfare") {
memberTotal += this.members[i].calculatePower();
}
}
return (0.0005 * memberTotal);
}
Gang.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("Gang", this);
}
Gang.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(Gang, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.Gang = Gang;
/*** Gang Member object ***/
function GangMember(name) {
this.name = name;
this.task = null; //GangMemberTask object
this.city = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].city;
//Name of upgrade only
this.weaponUpgrade = null;
this.armorUpgrade = null;
this.vehicleUpgrade = null;
this.hackingUpgrade = null;
this.hack = 1;
this.str = 1;
this.def = 1;
this.dex = 1;
this.agi = 1;
this.cha = 1;
this.hack_exp = 0;
this.str_exp = 0;
this.def_exp = 0;
this.dex_exp = 0;
this.agi_exp = 0;
this.cha_exp = 0;
this.hack_mult = 1;
this.str_mult = 1;
this.def_mult = 1;
this.dex_mult = 1;
this.agi_mult = 1;
this.cha_mult = 1;
}
//Same formula for Player
GangMember.prototype.calculateSkill = function(exp) {
return Math.max(Math.floor(32 * Math.log(exp + 534.5) - 200), 1);
}
GangMember.prototype.updateSkillLevels = function() {
this.hack = Math.floor(this.calculateSkill(this.hack_exp) * this.hack_mult);
this.str = Math.floor(this.calculateSkill(this.str_exp) * this.str_mult);
this.def = Math.floor(this.calculateSkill(this.def_exp) * this.def_mult);
this.dex = Math.floor(this.calculateSkill(this.dex_exp) * this.dex_mult);
this.agi = Math.floor(this.calculateSkill(this.agi_exp) * this.agi_mult);
this.cha = Math.floor(this.calculateSkill(this.cha_exp) * this.cha_mult);
}
GangMember.prototype.calculatePower = function() {
return (this.hack + this.str + this.def +
this.dex + this.agi + this.cha) / 100;
}
GangMember.prototype.assignToTask = function(taskName) {
if (GangMemberTasks.hasOwnProperty(taskName)) {
this.task = GangMemberTasks[taskName];
} else {
console.log("ERROR: Invalid task " + taskName);
this.task = null;
}
}
//Gains are per cycle
GangMember.prototype.calculateRespectGain = function() {
var task = this.task;
if (task === null || !(task instanceof GangMemberTask) || task.baseRespect === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (3.5 * task.difficulty);
if (statWeight <= 0) {return 0;}
var territoryMult = AllGangs[__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName].territory;
if (territoryMult <= 0) {return 0;}
var respectMult = (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect) / (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.wanted);
return 12 * task.baseRespect * statWeight * territoryMult * respectMult;
}
GangMember.prototype.calculateWantedLevelGain = function() {
var task = this.task;
if (task === null || !(task instanceof GangMemberTask) || task.baseWanted === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (3.5 * task.difficulty);
if (statWeight <= 0) {return 0;}
var territoryMult = AllGangs[__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName].territory;
if (territoryMult <= 0) {return 0;}
if (task.baseWanted < 0) {
return task.baseWanted * statWeight * territoryMult;
} else {
return 6 * task.baseWanted / (3 * statWeight * territoryMult);
}
}
GangMember.prototype.calculateMoneyGain = function() {
var task = this.task;
if (task === null || !(task instanceof GangMemberTask) || task.baseMoney === 0) {return 0;}
var statWeight = (task.hackWeight/100) * this.hack +
(task.strWeight/100) * this.str +
(task.defWeight/100) * this.def +
(task.dexWeight/100) * this.dex +
(task.agiWeight/100) * this.agi +
(task.chaWeight/100) * this.cha;
statWeight -= (3.5 * task.difficulty);
if (statWeight <= 0) {return 0;}
var territoryMult = AllGangs[__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName].territory;
if (territoryMult <= 0) {return 0;}
var respectMult = (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect) / (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect + __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.wanted);
return 5 * task.baseMoney * statWeight * territoryMult * respectMult;
}
GangMember.prototype.gainExperience = function(numCycles=1) {
var task = this.task;
if (task === null || !(task instanceof GangMemberTask)) {return;}
this.hack_exp += (task.hackWeight / 1500) * task.difficulty * numCycles;
this.str_exp += (task.strWeight / 1500) * task.difficulty * numCycles;
this.def_exp += (task.defWeight / 1500) * task.difficulty * numCycles;
this.dex_exp += (task.dexWeight / 1500) * task.difficulty * numCycles;
this.agi_exp += (task.agiWeight / 1500) * task.difficulty * numCycles;
this.cha_exp += (task.chaWeight / 1500) * task.difficulty * numCycles;
}
GangMember.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("GangMember", this);
}
GangMember.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(GangMember, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.GangMember = GangMember;
//Defines tasks that Gang Members can work on
function GangMemberTask(name="", desc="",
params={baseRespect: 0, baseWanted: 0, baseMoney: 0,
hackWeight: 0, strWeight: 0, defWeight: 0,
dexWeight: 0, agiWeight: 0, chaWeight: 0,
difficulty: 0}) {
this.name = name;
this.desc = desc;
this.baseRespect = params.baseRespect ? params.baseRespect : 0;
this.baseWanted = params.baseWanted ? params.baseWanted : 0;
this.baseMoney = params.baseMoney ? params.baseMoney : 0;
//Weights must add up to 100
this.hackWeight = params.hackWeight ? params.hackWeight : 0;
this.strWeight = params.strWeight ? params.strWeight : 0;
this.defWeight = params.defWeight ? params.defWeight : 0;
this.dexWeight = params.dexWeight ? params.dexWeight : 0;
this.agiWeight = params.agiWeight ? params.agiWeight : 0;
this.chaWeight = params.chaWeight ? params.chaWeight : 0;
//1 - 100
this.difficulty = params.difficulty ? params.difficulty : 1;
}
GangMemberTask.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("GangMemberTask", this);
}
GangMemberTask.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(GangMemberTask, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.GangMemberTask = GangMemberTask;
//TODO Human trafficking and an equivalent hacking crime
let GangMemberTasks = {
"Ransomware" : new GangMemberTask(
"Ransomware",
"Assign this gang member to create and distribute ransomware<br><br>" +
"Earns money - Slightly increases respect - Slightly increases wanted level",
{baseRespect: 0.00005, baseWanted: 0.00001, baseMoney: 1,
hackWeight: 100, difficulty: 1}),
"Phishing" : new GangMemberTask(
"Phishing",
"Assign this gang member to attempt phishing scams and attacks<br><br>" +
"Earns money - Slightly increases respect - Slightly increases wanted level",
{baseRespect: 0.00008, baseWanted: 0.001, baseMoney: 2.5,
hackWeight: 85, chaWeight: 15, difficulty: 3}),
"Identity Theft" : new GangMemberTask(
"Identity Theft",
"Assign this gang member to attempt identity theft<br><br>" +
"Earns money - Increases respect - Increases wanted level",
{baseRespect: 0.0001, baseWanted: 0.01, baseMoney: 6,
hackWeight: 80, chaWeight: 20, difficulty: 4}),
"DDoS Attacks" : new GangMemberTask(
"DDoS Attacks",
"Assign this gang member to carry out DDoS attacks<br><br>" +
"Increases respect - Increases wanted level",
{baseRespect: 0.0004, baseWanted: 0.05,
hackWeight: 100, difficulty: 7}),
"Plant Virus" : new GangMemberTask(
"Plant Virus",
"Assign this gang member to create and distribute malicious viruses<br><br>" +
"Increases respect - Increases wanted level",
{baseRespect: 0.0006, baseWanted: 0.05,
hackWeight: 100, difficulty: 10}),
"Fraud & Counterfeiting" : new GangMemberTask(
"Fraud & Counterfeiting",
"Assign this gang member to commit financial fraud and digital counterfeiting<br><br>" +
"Earns money - Slightly increases respect - Slightly increases wanted level",
{baseRespect: 0.0005, baseWanted: 0.1, baseMoney: 15,
hackWeight: 80, chaWeight: 20, difficulty: 17}),
"Money Laundering" : new GangMemberTask(
"Money Laundering",
"Assign this gang member to launder money<br><br>" +
"Earns money - Increases respect - Increases wanted level",
{baseRespect: 0.0006, baseWanted:0.2, baseMoney: 40,
hackWeight: 75, chaWeight: 25, difficulty: 20}),
"Cyberterrorism" : new GangMemberTask(
"Cyberterrorism",
"Assign this gang member to commit acts of cyberterrorism<br><br>" +
"Greatly increases respect - Greatly increases wanted level",
{baseRespect: 0.001, baseWanted: 0.5,
hackWeight: 80, chaWeight: 20, difficulty: 33}),
"Ethical Hacking" : new GangMemberTask(
"Ethical Hacking",
"Assign this gang member to be an ethical hacker for corporations<br><br>" +
"Earns money - Lowers wanted level",
{baseWanted: -0.001, baseMoney: 1,
hackWeight: 90, chaWeight: 10, difficulty: 1}),
"Mug People" : new GangMemberTask(
"Mug People",
"Assign this gang member to mug random people on the streets<br><br>" +
"Earns money - Slightly increases respect - Very slightly increases wanted level",
{baseRespect: 0.00005, baseWanted: 0.00001, baseMoney: 1,
strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 10, chaWeight: 15, difficulty: 1}),
"Deal Drugs" : new GangMemberTask(
"Deal Drugs",
"Assign this gang member to sell drugs.<br><br>" +
"Earns money - Slightly increases respect - Slightly increases wanted level",
{baseRespect: 0.00008, baseWanted: 0.001, baseMoney: 4,
agiWeight: 20, dexWeight: 20, chaWeight: 60, difficulty: 3}),
"Run a Con" : new GangMemberTask(
"Run a Con",
"Assign this gang member to run cons<br><br>" +
"Earns money - Increases respect - Increases wanted level",
{baseRespect: 0.00015, baseWanted: 0.01, baseMoney: 10,
strWeight: 5, defWeight: 5, agiWeight: 25, dexWeight: 25, chaWeight: 40, difficulty: 10}),
"Armed Robbery" : new GangMemberTask(
"Armed Robbery",
"Assign this gang member to commit armed robbery on stores, banks and armored cars<br><br>" +
"Earns money - Increases respect - Increases wanted level",
{baseRespect: 0.00015, baseWanted: 0.05, baseMoney: 25,
hackWeight: 20, strWeight: 15, defWeight: 15, agiWeight: 10, dexWeight: 20, chaWeight: 20,
difficulty: 17}),
"Traffick Illegal Arms" : new GangMemberTask(
"Traffick Illegal Arms",
"Assign this gang member to traffick illegal arms<br><br>" +
"Earns money - Increases respect - Increases wanted level",
{baseRespect: 0.0003, baseWanted: 0.1, baseMoney: 40,
hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, chaWeight: 75,
difficulty: 25}),
"Threaten & Blackmail" : new GangMemberTask(
"Threaten & Blackmail",
"Assign this gang member to threaten and black mail high-profile targets<br><br>" +
"Earns money - Slightly increases respect - Slightly increases wanted level",
{baseRespect: 0.0002, baseWanted: 0.05, baseMoney: 15,
hackWeight: 25, strWeight: 25, dexWeight: 25, chaWeight: 25, difficulty: 28}),
"Terrorism" : new GangMemberTask(
"Terrorism",
"Assign this gang member to commit acts of terrorism<br><br>" +
"Greatly increases respect - Greatly increases wanted level",
{baseRespect: 0.001, baseWanted: 1,
hackWeight: 20, strWeight: 20, defWeight: 20,dexWeight: 20, chaWeight: 20,
difficulty: 33}),
"Vigilante Justice" : new GangMemberTask(
"Vigilante Justice",
"Assign this gang member to be a vigilante and protect the city from criminals<br><br>" +
"Decreases wanted level",
{baseWanted: -0.001,
hackWeight: 20, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight:20,
difficulty: 1}),
"Train Combat" : new GangMemberTask(
"Train Combat",
"Assign this gang member to increase their combat stats (str, def, dex, agi)",
{strWeight: 25, defWeight: 25, dexWeight: 25, agiWeight: 25, difficulty: 5}),
"Train Hacking" : new GangMemberTask(
"Train Hacking",
"Assign this gang member to train their hacking skills",
{hackWeight: 100, difficulty: 8}),
"Territory Warfare" : new GangMemberTask(
"Territory Warfare",
"Assign this gang member to engage in territorial warfare with other gangs. " +
"Members assigned to this task will help increase your gang's territory " +
"and will defend your territory from being taken.",
{hackWeight: 15, strWeight: 20, defWeight: 20, dexWeight: 20, agiWeight: 20,
chaWeight: 5, difficulty: 3}),
}
function GangMemberUpgrade(name="", desc="", cost=0, type="-") {
this.name = name;
this.desc = desc;
this.cost = cost;
this.type = type; //w, a, v, r
}
//Passes in a GangMember object
GangMemberUpgrade.prototype.apply = function(member, unapply=false) {
switch(this.name) {
case "Baseball Bat":
unapply ? member.str_mult /= 1.1 : member.str_mult *= 1.1;
unapply ? member.def_mult /= 1.1 : member.def_mult *= 1.1;
break;
case "Katana":
unapply ? member.str_mult /= 1.15 : member.str_mult *= 1.15;
unapply ? member.def_mult /= 1.15 : member.def_mult *= 1.15;
unapply ? member.dex_mult /= 1.15 : member.dex_mult *= 1.15;
break;
case "Glock 18C":
unapply ? member.str_mult /= 1.2 : member.str_mult *= 1.2;
unapply ? member.def_mult /= 1.2 : member.def_mult *= 1.2;
unapply ? member.dex_mult /= 1.2 : member.dex_mult *= 1.2;
unapply ? member.agi_mult /= 1.2 : member.agi_mult *= 1.2;
break;
case "P90":
unapply ? member.str_mult /= 1.4 : member.str_mult *= 1.4;
unapply ? member.def_mult /= 1.4 : member.def_mult *= 1.4;
unapply ? member.agi_mult /= 1.2 : member.agi_mult *= 1.2;
break;
case "Steyr AUG":
unapply ? member.str_mult /= 1.6 : member.str_mult *= 1.6;
unapply ? member.def_mult /= 1.6 : member.def_mult *= 1.6;
break;
case "AK-47":
unapply ? member.str_mult /= 1.8 : member.str_mult *= 1.8;
unapply ? member.def_mult /= 1.8 : member.def_mult *= 1.8;
break;
case "M15A10 Assault Rifle":
unapply ? member.str_mult /= 1.9 : member.str_mult *= 1.9;
unapply ? member.def_mult /= 1.9 : member.def_mult *= 1.9;
break;
case "AWM Sniper Rifle":
unapply ? member.str_mult /= 1.8 : member.str_mult *= 1.8;
unapply ? member.dex_mult /= 1.8 : member.dex_mult *= 1.8;
unapply ? member.agi_mult /= 1.8 : member.agi_mult *= 1.8;
break;
case "Bulletproof Vest":
unapply ? member.def_mult /= 1.15 : member.def_mult *= 1.15;
break;
case "Full Body Armor":
unapply ? member.def_mult /= 1.3 : member.def_mult *= 1.3;
break;
case "Liquid Body Armor":
unapply ? member.def_mult /= 1.5 : member.def_mult *= 1.5;
unapply ? member.agi_mult /= 1.5 : member.agi_mult *= 1.5;
break;
case "Graphene Plating Armor":
unapply ? member.def_mult /= 2 : member.def_mult *= 2;
break;
case "Ford Flex V20":
unapply ? member.agi_mult /= 1.2 : member.agi_mult *= 1.2;
unapply ? member.cha_mult /= 1.2 : member.cha_mult *= 1.2;
break;
case "ATX1070 Superbike":
unapply ? member.agi_mult /= 1.4 : member.agi_mult *= 1.4;
unapply ? member.cha_mult /= 1.4 : member.cha_mult *= 1.4;
break;
case "Mercedes-Benz S9001":
unapply ? member.agi_mult /= 1.6 : member.agi_mult *= 1.6;
unapply ? member.cha_mult /= 1.6 : member.cha_mult *= 1.6;
break;
case "White Ferrari":
unapply ? member.agi_mult /= 1.8 : member.agi_mult *= 1.8;
unapply ? member.cha_mult /= 1.8 : member.cha_mult *= 1.8;
break;
case "NUKE Rootkit":
unapply ? member.hack_mult /= 1.2 : member.hack_mult *= 1.2;
break;
case "Soulstealer Rootkit":
unapply ? member.hack_mult /= 1.3 : member.hack_mult *= 1.3;
break;
case "Demon Rootkit":
unapply ? member.hack_mult /= 1.5 : member.hack_mult *= 1.5;
break;
default:
console.log("ERROR: Could not find this upgrade: " + this.name);
break;
}
}
//Purchases for given member
GangMemberUpgrade.prototype.purchase = function(memberObj) {
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(this.cost)) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase this upgrade");
return;
}
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(this.cost);
switch (this.type) {
case "w":
if (memberObj.weaponUpgrade instanceof GangMemberUpgrade) {
memberObj.weaponUpgrade.apply(memberObj, true); //Unapply old upgrade
}
this.apply(memberObj, false);
memberObj.weaponUpgrade = this;
break;
case "a":
if (memberObj.armorUpgrade instanceof GangMemberUpgrade) {
memberObj.armorUpgrade.apply(memberObj, true); //Unapply old upgrade
}
this.apply(memberObj, false);
memberObj.armorUpgrade = this;
break;
case "v":
if (memberObj.vehicleUpgrade instanceof GangMemberUpgrade) {
memberObj.vehicleUpgrade.apply(memberObj, true); //Unapply old upgrade
}
this.apply(memberObj, false);
memberObj.vehicleUpgrade = this;
break;
case "r":
if (memberObj.hackingUpgrade instanceof GangMemberUpgrade) {
memberObj.hackingUpgrade.apply(memberObj, true); //Unapply old upgrade
}
this.apply(memberObj, false);
memberObj.hackingUpgrade = this;
break;
default:
console.log("ERROR: GangMemberUpgrade has invalid type: " + this.type);
break;
}
createGangMemberUpgradeBox(memberObj);
}
GangMemberUpgrade.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["b" /* Generic_toJSON */])("GangMemberUpgrade", this);
}
GangMemberUpgrade.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(GangMemberUpgrade, value.data);
}
__WEBPACK_IMPORTED_MODULE_6__utils_JSONReviver_js__["c" /* Reviver */].constructors.GangMemberUpgrade = GangMemberUpgrade;
let GangMemberUpgrades = {
"Baseball Bat" : new GangMemberUpgrade("Baseball Bat",
"Increases strength and defense by 10%", 1000000, "w"),
"Katana" : new GangMemberUpgrade("Katana",
"Increases strength, defense, and dexterity by 15%", 12000000, "w"),
"Glock 18C" : new GangMemberUpgrade("Glock 18C",
"Increases strength, defense, dexterity, and agility by 20%", 25000000, "w"),
"P90" : new GangMemberUpgrade("P90C",
"Increases strength and defense by 40%. Increases agility by 20%", 50000000, "w"),
"Steyr AUG" : new GangMemberUpgrade("Steyr AUG",
"Increases strength and defense by 60%", 60000000, "w"),
"AK-47" : new GangMemberUpgrade("AK-47",
"Increases strength and defense by 80%", 100000000, "w"),
"M15A10 Assault Rifle" : new GangMemberUpgrade("M15A10 Assault Rifle",
"Increases strength and defense by 90%", 150000000, "w"),
"AWM Sniper Rifle" : new GangMemberUpgrade("AWM Sniper Rifle",
"Increases strength, dexterity, and agility by 80%", 225000000, "w"),
"Bulletproof Vest" : new GangMemberUpgrade("Bulletproof Vest",
"Increases defense by 15%", 2000000, "a"),
"Full Body Armor" : new GangMemberUpgrade("Full Body Armor",
"Increases defense by 30%", 5000000, "a"),
"Liquid Body Armor" : new GangMemberUpgrade("Liquid Body Armor",
"Increases defense and agility by 50%", 25000000, "a"),
"Graphene Plating Armor" : new GangMemberUpgrade("Graphene Plating Armor",
"Increases defense by 100%", 40000000, "a"),
"Ford Flex V20" : new GangMemberUpgrade("Ford Flex V20",
"Increases agility and charisma by 20%", 3000000, "v"),
"ATX1070 Superbike" : new GangMemberUpgrade("ATX1070 Superbike",
"Increases agility and charisma by 40%", 9000000, "v"),
"Mercedes-Benz S9001" : new GangMemberUpgrade("Mercedes-Benz S9001",
"Increases agility and charisma by 60%", 18000000, "v"),
"White Ferrari" : new GangMemberUpgrade("White Ferrari",
"Increases agility and charisma by 80%", 30000000, "v"),
"NUKE Rootkit" : new GangMemberUpgrade("NUKE Rootkit",
"Increases hacking by 20%", 5000000, "r"),
"Soulstealer Rootkit" : new GangMemberUpgrade("Soulstealer Rootkit",
"Increases hacking by 30%", 15000000, "r"),
"Demon Rootkit" : new GangMemberUpgrade("Demon Rootkit",
"Increases hacking by 50%", 50000000, "r"),
}
//Create a pop-up box that lets player purchase upgrades
let gangMemberUpgradeBoxOpened = false;
function createGangMemberUpgradeBox(memberObj) {
console.log("Creating gang member upgrade box for " + memberObj.name);
var container = document.getElementById("gang-purchase-upgrade-container");
if (container) {
while (container.firstChild) {
container.removeChild(container.firstChild);
}
} else {
var container = document.createElement("div");
container.setAttribute("id", "gang-purchase-upgrade-container");
document.getElementById("entire-game-container").appendChild(container);
container.setAttribute("class", "dialog-box-container");
container.style.display = "block";
}
var content = document.createElement("div");
content.setAttribute("class", "dialog-box-content");
content.setAttribute("id", "gang-purchase-upgrade-content");
container.appendChild(content);
var intro = document.createElement("p");
content.appendChild(intro);
intro.innerHTML =
memberObj.name + "<br><br>" +
"A gang member can be upgraded with a weapon, armor, a vehicle, and a hacking rootkit. " +
"For each of these pieces of equipment, a gang member can only have one at a time (i.e " +
"a member cannot have two weapons or two vehicles). Purchasing an upgrade will automatically " +
"replace the member's existing upgrade, if he/she is equipped with one. The existing upgrade " +
"will be lost and will have to be re-purchased if you want to switch back.<br><br>";
//Weapons
var weaponTxt = document.createElement("p");
weaponTxt.style.display = "block";
content.appendChild(weaponTxt);
if (memberObj.weaponUpgrade instanceof GangMemberUpgrade) {
weaponTxt.innerHTML = "Weapons (Current Equip: " + memberObj.weaponUpgrade.name + ")";
} else {
weaponTxt.innerHTML = "Weapons (Current Equip: NONE)";
}
var weaponNames = ["Baseball Bat", "Katana", "Glock 18C", "P90", "Steyr AUG",
"AK-47", "M15A10 Assault Rifle", "AWM Sniper Rifle"];
createGangMemberUpgradeButtons(memberObj, weaponNames, memberObj.weaponUpgrade, content);
content.appendChild(document.createElement("br"));
var armorTxt = document.createElement("p");
armorTxt.style.display = "block";
content.appendChild(armorTxt);
if (memberObj.armorUpgrade instanceof GangMemberUpgrade) {
armorTxt.innerHTML = "Armor (Current Equip: " + memberObj.armorUpgrade.name + ")";
} else {
armorTxt.innerHTML = "Armor (Current Equip: NONE)";
}
var armorNames = ["Bulletproof Vest", "Full Body Armor", "Liquid Body Armor",
"Graphene Plating Armor"];
createGangMemberUpgradeButtons(memberObj, armorNames, memberObj.armorUpgrade, content);
var vehicleTxt = document.createElement("p");
vehicleTxt.style.display = "block";
content.appendChild(vehicleTxt);
if (memberObj.vehicleUpgrade instanceof GangMemberUpgrade) {
vehicleTxt.innerHTML = "Vehicles (Current Equip: " + memberObj.vehicleUpgrade.name + ")";
} else {
vehicleTxt.innerHTML = "Vehicles (Current Equip: NONE)";
}
var vehicleNames = ["Ford Flex V20", "ATX1070 Superbike", "Mercedes-Benz S9001",
"White Ferrari"];
createGangMemberUpgradeButtons(memberObj, vehicleNames, memberObj.vehicleUpgrade, content);
var rootkitTxt = document.createElement("p");
rootkitTxt.style.display = "block";
content.appendChild(rootkitTxt);
if (memberObj.hackingUpgrade instanceof GangMemberUpgrade) {
rootkitTxt.innerHTML = "Rootkits (Current Equip: " + memberObj.hackingUpgrade.name + ")";
} else {
rootkitTxt.innerHTML = "Rootkits (Current Equip: NONE)";
}
var rootkitNames = ["NUKE Rootkit", "Soulstealer Rootkit", "Demon Rootkit"];
createGangMemberUpgradeButtons(memberObj, rootkitNames, memberObj.hackingUpgrade, content);
gangMemberUpgradeBoxOpened = true;
}
function createGangMemberUpgradeButtons(memberObj, upgNames, memberUpgrade, content) {
for (var i = 0; i < upgNames.length; ++i) {
(function() {
var upgrade = GangMemberUpgrades[upgNames[i]];
if (upgrade == null) {
console.log("ERROR: Could not find GangMemberUpgrade object for" + upgNames[i]);
return; //Return inside closure
}
//Skip the currently owned upgrade
if (memberUpgrade instanceof GangMemberUpgrade &&
memberUpgrade.name == upgrade.name) {return;}
//Create button
var btn = document.createElement("a");
btn.innerHTML = upgrade.name + " - $" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(upgrade.cost).format('(0.00a)');
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gte(upgrade.cost)) {
btn.setAttribute("class", "popup-box-button tooltip")
} else {
btn.setAttribute("class", "popup-box-button-inactive tooltip");
}
btn.style.cssFloat = "none";
btn.style.display = "block";
btn.style.margin = "8px";
btn.style.width = "40%";
//Tooltip for upgrade
var tooltip = document.createElement("span");
tooltip.setAttribute("class", "tooltiptext");
tooltip.innerHTML = upgrade.desc;
btn.appendChild(tooltip);
content.appendChild(btn);
btn.addEventListener("click", function() {
upgrade.purchase(memberObj);
});
}()); // Immediate invocation
}
}
let gangContentCreated = false;
function displayGangContent() {
if (!gangContentCreated) {
gangContentCreated = true;
//Create gang container
var container = document.createElement("div");
document.getElementById("entire-game-container").appendChild(container);
container.setAttribute("id", "gang-container");
container.setAttribute("class", "generic-menupage-container");
//Get variables
var facName = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName;
var members = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members;
var wanted = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.wanted;
var respect = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect;
//Buttons to switch between panels
var managementButton = document.createElement("a");
managementButton.setAttribute("id", "gang-management-subpage-button");
managementButton.innerHTML = "Gang Management (1)";
managementButton.setAttribute("class", "a-link-button-inactive");
managementButton.style.display = "inline-block";
var territoryButton = document.createElement("a");
territoryButton.setAttribute("id", "gang-territory-subpage-button");
territoryButton.innerHTML = "Gang Territory (2)";
territoryButton.setAttribute("class", "a-link-button");
territoryButton.style.display = "inline-block";
managementButton.addEventListener("click", function() {
document.getElementById("gang-management-subpage").style.display = "block";
document.getElementById("gang-territory-subpage").style.display = "none";
managementButton.classList.toggle("a-link-button-inactive");
managementButton.classList.toggle("a-link-button");
territoryButton.classList.toggle("a-link-button-inactive");
territoryButton.classList.toggle("a-link-button");
updateGangContent();
return false;
});
territoryButton.addEventListener("click", function() {
document.getElementById("gang-management-subpage").style.display = "none";
document.getElementById("gang-territory-subpage").style.display = "block";
managementButton.classList.toggle("a-link-button-inactive");
managementButton.classList.toggle("a-link-button");
territoryButton.classList.toggle("a-link-button-inactive");
territoryButton.classList.toggle("a-link-button");
updateGangContent();
return false;
});
container.appendChild(managementButton);
container.appendChild(territoryButton);
//Subpage for managing gang members
var managementSubpage = document.createElement("div");
container.appendChild(managementSubpage);
managementSubpage.style.display = "block";
managementSubpage.setAttribute("id", "gang-management-subpage");
var infoText = document.createElement("p");
managementSubpage.appendChild(infoText);
infoText.setAttribute("id", "gang-info");
infoText.style.width = "70%";
var recruitGangMemberBtn = document.createElement("a");
managementSubpage.appendChild(recruitGangMemberBtn);
recruitGangMemberBtn.setAttribute("id", "gang-management-recruit-member-btn");
recruitGangMemberBtn.setAttribute("class", "a-link-button-inactive");
recruitGangMemberBtn.innerHTML = "Recruit Gang Member";
recruitGangMemberBtn.style.display = "inline-block";
recruitGangMemberBtn.style.margin = "10px";
recruitGangMemberBtn.addEventListener("click", () => {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["j" /* yesNoTxtInpBoxGetYesButton */])(), noBtn = Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["i" /* yesNoTxtInpBoxGetNoButton */])();
yesBtn.innerHTML = "Recruit Gang Member";
noBtn.innerHTML = "Cancel";
yesBtn.addEventListener("click", ()=>{
var name = Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])();
if (name == "") {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You must enter a name for your Gang member!");
} else {
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members.length; ++i) {
if (name == __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members[i].name) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You already have a gang member with this name!");
return false;
}
}
var member = new GangMember(name);
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members.push(member);
createGangMemberDisplayElement(member);
updateGangContent();
}
Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])();
});
noBtn.addEventListener("click", ()=>{
Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["f" /* yesNoTxtInpBoxClose */])();
});
Object(__WEBPACK_IMPORTED_MODULE_10__utils_YesNoBox_js__["g" /* yesNoTxtInpBoxCreate */])("Please enter a name for your new Gang member:");
return false;
});
//Text for how much reputation is required for recruiting next memberList
var recruitRequirementText = document.createElement("p");
managementSubpage.appendChild(recruitRequirementText);
recruitRequirementText.setAttribute("id", "gang-recruit-requirement-text");
recruitRequirementText.style.color = "red";
var memberList = document.createElement("ul");
managementSubpage.appendChild(memberList);
memberList.setAttribute("id", "gang-member-list");
for (var i = 0; i < members.length; ++i) {
createGangMemberDisplayElement(members[i]);
}
setGangMemberClickHandlers(); //Set buttons to toggle the gang member info panels
//Subpage for seeing gang territory information
var territorySubpage = document.createElement("div");
container.appendChild(territorySubpage);
territorySubpage.setAttribute("id", "gang-territory-subpage");
territorySubpage.style.display = "none";
//Info text for territory page
var territoryInfoText = document.createElement("p");
territorySubpage.appendChild(territoryInfoText);
territoryInfoText.innerHTML =
"This page shows how much territory your Gang controls. This statistic is listed as a percentage, " +
"which represents how much of the total territory you control.<br><br>" +
"Territory gain and loss is processed automatically and is updated every ~30 seconds. Your chances " +
"to gain and lose territory depend on your Gang's power, which is listed in the display below. " +
"Your gang's power is determined by the stats of all Gang members you have assigned to the " +
"'Territory Warfare' task. Gang members that are not assigned to this task do not contribute to " +
"your Gang's power.<br><br>" +
"The amount of territory you have affects all aspects of your Gang members' production, including " +
"money, respect, and wanted level. It is very beneficial to have high territory control.<br><br>"
territoryInfoText.style.width = "70%";
var territoryBorder = document.createElement("fieldset");
territoryBorder.style.width = "50%";
territoryBorder.style.display = "inline-block";
var territoryP = document.createElement("p");
territoryP.setAttribute("id", "gang-territory-info");
territoryBorder.appendChild(territoryP);
territorySubpage.appendChild(territoryBorder);
}
document.getElementById("gang-container").style.visibility = "visible";
updateGangContent();
}
function updateGangContent() {
if (!gangContentCreated || !__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].inGang()) {return;}
if(document.getElementById("gang-territory-subpage").style.display === "block") {
//Update territory information
var elem = document.getElementById("gang-territory-info");
elem.innerHTML = "";
for (var gangname in AllGangs) {
if (AllGangs.hasOwnProperty(gangname)) {
var gangInfo = AllGangs[gangname];
if (gangname == __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName) {
elem.innerHTML += ("<b>" + gangname + "</b><br>(Power: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gangInfo.power, 6) + "): " +
Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(100*gangInfo.territory, 2) + "%<br><br>");
} else {
elem.innerHTML += (gangname + "<br>(Power: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gangInfo.power, 6) + "): " +
Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(100*gangInfo.territory, 2) + "%<br><br>");
}
}
}
} else {
//Update information for overall gang
var gangInfo = document.getElementById("gang-info");
if (gangInfo) {
var faction = __WEBPACK_IMPORTED_MODULE_2__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName];
var rep;
if (!(faction instanceof __WEBPACK_IMPORTED_MODULE_2__Faction_js__["a" /* Faction */])) {
rep = "ERROR";
} else {
rep = faction.playerReputation;
}
gangInfo.innerHTML =
"<p>This page is used to manage your gang members and get an overview of your gang's stats. <br><br>" +
"If a gang member is not earning much money or respect, the task that you have assigned to that member " +
"might be too difficult. Consider training that member's stats or choosing an easier task. The tasks closer to the " +
"top of the dropdown list are generally easier. Alternatively, the gang member's low production might be due to the " +
"fact that your wanted level is too high. Consider assigning a few members to the 'Vigilante Justice' or 'Ethical Hacking' " +
"tasks to lower your wanted level. <br><br>" +
"Installing Augmentations does NOT reset your progress with your Gang. Furthermore, after installing Augmentations, you will " +
"automatically be a member of whatever Faction you created your gang with.<br><br>" +
"<p class='tooltip'>Respect: <span class='tooltiptext'>Represents the amount of respect " +
"your gang has from other gangs and criminal organizations. Your respect affects the amount of money " +
"your gang members will earn, and also determines how much reputation you are earning with your gang's " +
"correpsonding Faction.</span></p><p>" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respect, 6) + " (" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.respectGainRate, 6) + " / sec)</p><br>" +
"<p class='tooltip'>Wanted Level: <span class='tooltiptext'>Represents how much the gang is wanted by law " +
"enforcement. The higher your gang's wanted level, the harder it will be for your gang members to make " +
"money and earn respect. Note that the minimum respect value is 1." +
"</span></p><p>" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.wanted, 6) + " (" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.wantedGainRate, 6) + " / sec)<br><br>" +
"Money gain rate: $" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.moneyGainRate, 2) + " / sec<br><br>" +
"Faction reputation: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(rep, 3) + "</p>";
} else {
console.log("ERROR: gang-info DOM element DNE");
}
//Toggle the 'Recruit member button' if valid
var numMembers = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members.length;
var repCost = 0;
if (numMembers > 0) {
var repCost = Math.pow(__WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].GangRecruitCostMultiplier, numMembers);
}
var faction = __WEBPACK_IMPORTED_MODULE_2__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.facName];
if (faction === null) {
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Could not find your gang's faction. This is probably a bug please report to dev");
return;
}
var btn = document.getElementById("gang-management-recruit-member-btn");
if (numMembers >= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaximumGangMembers) {
btn.className = "a-link-button-inactive";
document.getElementById("gang-recruit-requirement-text").style.display = "block";
document.getElementById("gang-recruit-requirement-text").innerHTML =
"You have reached the maximum amount of gang members";
} else if (faction.playerReputation >= repCost) {
btn.className = "a-link-button";
document.getElementById("gang-recruit-requirement-text").style.display = "none";
} else {
btn.className = "a-link-button-inactive";
document.getElementById("gang-recruit-requirement-text").style.display = "block";
document.getElementById("gang-recruit-requirement-text").innerHTML =
Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(repCost, 2) + " Faction reputation needed to recruit next member";
}
//Update information for each gang member
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members.length; ++i) {
updateGangMemberDisplayElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.members[i]);
}
}
}
function setGangMemberClickHandlers() {
//Server panel click handlers
var gangMemberHdrs = document.getElementsByClassName("gang-member-header");
if (gangMemberHdrs == null) {
console.log("ERROR: Could not find Active Scripts server panels");
return;
}
for (let i = 0; i < gangMemberHdrs.length; ++i) {
gangMemberHdrs[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
}
//Takes in a GangMember object
function createGangMemberDisplayElement(memberObj) {
if (!gangContentCreated || !__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].inGang()) {return;}
var name = memberObj.name;
var li = document.createElement("li");
var hdr = document.createElement("button");
hdr.setAttribute("class", "gang-member-header");
hdr.setAttribute("id", name + "-gang-member-hdr");
hdr.innerHTML = name;
//Div for entire panel
var gangMemberDiv = document.createElement("div");
gangMemberDiv.setAttribute("class", "gang-member-panel");
//Gang member content divided into 3 panels:
//Stats Panel
var statsDiv = document.createElement("div");
statsDiv.setAttribute("id", name + "gang-member-stats");
statsDiv.setAttribute("class", "gang-member-info-div");
var statsP = document.createElement("p");
statsP.setAttribute("id", name + "gang-member-stats-text");
statsP.style.display = "inline";
var upgradeButton = document.createElement("a");
upgradeButton.setAttribute("id", name + "gang-member-upgrade-btn");
upgradeButton.setAttribute("class", "popup-box-button");
upgradeButton.style.cssFloat = "left";
upgradeButton.innerHTML = "Purchase Upgrades";
upgradeButton.addEventListener("click", function() {
createGangMemberUpgradeBox(memberObj);
});
statsDiv.appendChild(statsP);
statsDiv.appendChild(upgradeButton);
//Panel for Selecting task and show respect/wanted gain
var taskDiv = document.createElement("div");
taskDiv.setAttribute("id", name + "gang-member-task");
taskDiv.setAttribute("class", "gang-member-info-div");
var taskSelector = document.createElement("select");
taskSelector.style.color = "white";
taskSelector.style.backgroundColor = "black";
taskSelector.setAttribute("id", name + "gang-member-task-selector");
var tasks = null;
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gang.isHackingGang) {
tasks = ["---", "Ransomware", "Phishing", "Identity Theft", "DDoS Attacks",
"Plant Virus", "Fraud & Counterfeiting","Money Laundering",
"Cyberterrorism", "Ethical Hacking", "Train Combat",
"Train Hacking", "Territory Warfare"];
} else {
tasks = ["---", "Mug People", "Deal Drugs", "Run a Con", "Armed Robbery",
"Traffick Illegal Arms", "Threaten & Blackmail",
"Terrorism", "Vigilante Justice", "Train Combat",
"Train Hacking", "Territory Warfare"];
}
for (var i = 0; i < tasks.length; ++i) {
var option = document.createElement("option");
option.text = tasks[i];
taskSelector.add(option);
}
taskSelector.addEventListener("change", function() {
var task = taskSelector.options[taskSelector.selectedIndex].text;
memberObj.assignToTask(task);
setGangMemberTaskDescription(memberObj, task);
updateGangContent();
});
//Set initial task in selector element
if (memberObj.task instanceof GangMemberTask) {
var taskName = memberObj.task.name;
var taskIndex = 0;
for (let i = 0; i < tasks.length; ++i) {
if (taskName == tasks[i]) {
taskIndex = i;
break;
}
}
taskSelector.selectedIndex = taskIndex;
}
var gainInfo = document.createElement("p"); //Wanted, respect, reputation, and money gain
gainInfo.setAttribute("id", name + "gang-member-gain-info");
taskDiv.appendChild(taskSelector);
taskDiv.appendChild(gainInfo);
//Panel for Description of task
var taskDescDiv = document.createElement("div");
taskDescDiv.setAttribute("id", name + "gang-member-task-desc");
taskDescDiv.setAttribute("class", "gang-member-info-div");
var taskDescP = document.createElement("p");
taskDescP.setAttribute("id", name + "gang-member-task-description");
taskDescP.style.display = "inline";
taskDescDiv.appendChild(taskDescP);
statsDiv.style.width = "30%";
taskDiv.style.width = "30%";
taskDescDiv.style.width = "30%";
statsDiv.style.display = "inline";
taskDiv.style.display = "inline";
taskDescDiv.style.display = "inline";
gangMemberDiv.appendChild(statsDiv);
gangMemberDiv.appendChild(taskDiv);
gangMemberDiv.appendChild(taskDescDiv);
li.appendChild(hdr);
li.appendChild(gangMemberDiv);
document.getElementById("gang-member-list").appendChild(li);
setGangMemberTaskDescription(memberObj, taskName); //Initialize description
setGangMemberClickHandlers(); //Reset click handlers
updateGangMemberDisplayElement(memberObj);
}
function updateGangMemberDisplayElement(memberObj) {
if (!gangContentCreated || !__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].inGang()) {return;}
var name = memberObj.name;
//TODO Add upgrade information
var stats = document.getElementById(name + "gang-member-stats-text");
if (stats) {
stats.innerHTML =
"Hacking: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.hack, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.hack_exp).format('(0.00a)') + " exp)<br>" +
"Strength: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.str, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.str_exp).format('(0.00a)') + " exp)<br>" +
"Defense: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.def, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.def_exp).format('(0.00a)') + " exp)<br>" +
"Dexterity: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.dex, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.dex_exp).format('(0.00a)') + " exp)<br>" +
"Agility: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.agi, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.agi_exp).format('(0.00a)') + " exp)<br>" +
"Charisma: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(memberObj.cha, 0) + " (" + __WEBPACK_IMPORTED_MODULE_8__utils_numeral_min_js___default()(memberObj.cha_exp).format('(0.00a)') + " exp)<br>";
}
var gainInfo = document.getElementById(name + "gang-member-gain-info");
if (gainInfo) {
gainInfo.innerHTML =
"Money: $" + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*memberObj.calculateMoneyGain(), 2) + " / sec<br>" +
"Respect: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*memberObj.calculateRespectGain(), 6) + " / sec<br>" +
"Wanted Level: " + Object(__WEBPACK_IMPORTED_MODULE_9__utils_StringHelperFunctions_js__["c" /* formatNumber */])(5*memberObj.calculateWantedLevelGain(), 6) + " / sec<br>";
}
}
function setGangMemberTaskDescription(memberObj, taskName) {
var name = memberObj.name;
var taskDesc = document.getElementById(name + "gang-member-task-description");
if (taskDesc) {
var task = GangMemberTasks[taskName];
if (task == null) {return;}
var desc = task.desc;
taskDesc.innerHTML = desc;
}
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SourceFiles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PlayerOwnedSourceFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return applySourceFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return initSourceFiles; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__BitNode_js__ = __webpack_require__(9);
/* SourceFile.js */
//Each SourceFile corresponds to a BitNode with the same number
function SourceFile(number, info="") {
var bitnodeKey = "BitNode" + number;
var bitnode = __WEBPACK_IMPORTED_MODULE_1__BitNode_js__["b" /* BitNodes */][bitnodeKey];
if (bitnode == null) {
throw new Error("Invalid Bit Node for this Source File");
}
this.n = number;
this.name = "Source-File " + number + ": " + bitnode.name;
this.lvl = 1;
this.info = info;
this.owned = false;
}
let SourceFiles = {};
function initSourceFiles() {
SourceFiles = {};
SourceFiles["SourceFile1"] = new SourceFile(1, "This Source-File lets the player start with 32GB of RAM on his/her " +
"home computer. It also increases all of the player's multipliers by:<br><br>" +
"Level 1: 16%<br>" +
"Level 2: 24%<br>" +
"Level 3: 28%");
SourceFiles["SourceFile2"] = new SourceFile(2, "This Source-File increases the player's crime success rate, crime money, and charisma " +
"multipliers by:<br><br>" +
"Level 1: 20%<br>" +
"Level 2: 30%<br>" +
"Level 3: 35%");
SourceFiles["SourceFile3"] = new SourceFile(3);
SourceFiles["SourceFile4"] = new SourceFile(4, "This Source-File lets you access and use the Singularity Functions in every BitNode. Every " +
"level of this Source-File opens up more of the Singularity Functions you can use.");
SourceFiles["SourceFile5"] = new SourceFile(5);
SourceFiles["SourceFile6"] = new SourceFile(6);
SourceFiles["SourceFile7"] = new SourceFile(7);
SourceFiles["SourceFile8"] = new SourceFile(8);
SourceFiles["SourceFile9"] = new SourceFile(9);
SourceFiles["SourceFile10"] = new SourceFile(10);
SourceFiles["SourceFile11"] = new SourceFile(11, "This Source-File increases the player's company salary and reputation gain multipliers by:<br><br>" +
"Level 1: 60%<br>" +
"Level 2: 90%<br>" +
"Level 3: 105%<br>");
SourceFiles["SourceFile12"] = new SourceFile(12);
}
function PlayerOwnedSourceFile(number, level) {
this.n = number;
this.lvl = level;
}
//Takes in a PlayerOwnedSourceFile as the "srcFile" argument
function applySourceFile(srcFile) {
var srcFileKey = "SourceFile" + srcFile.n;
var sourceFileObject = SourceFiles[srcFileKey];
if (sourceFileObject == null) {
console.log("ERROR: Invalid source file number: " + srcFile.n);
return;
}
switch(srcFile.n) {
case 1: // The Source Genesis
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (16 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
var decMult = 1 - (mult / 100);
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_chance_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_speed_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_money_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_grow_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacking_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].strength_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].defense_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].dexterity_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].agility_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_exp_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].faction_rep_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_money_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult *= decMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult *= decMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_core_cost_mult *= decMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].hacknet_node_level_cost_mult *= decMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult;
break;
case 2: //Rise of the Underworld
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (20 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_money_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].crime_success_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].charisma_mult *= incMult;
break;
case 4: //The Singularity
//No effects, just gives access to Singularity functions
break;
case 11: //The Big Crash
var mult = 0;
for (var i = 0; i < srcFile.lvl; ++i) {
mult += (60 / (Math.pow(2, i)));
}
var incMult = 1 + (mult / 100);
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].work_money_mult *= incMult;
__WEBPACK_IMPORTED_MODULE_0__Player_js__["a" /* Player */].company_rep_mult *= incMult;
break;
default:
console.log("ERROR: Invalid source file number: " + srcFile.n);
break;
}
sourceFileObject.owned = true;
}
/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return prestigeAugmentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return prestigeSourceFile; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ActiveScriptsUI_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Message_js__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__StockMarket_js__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__Terminal_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_decimal_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_15__utils_decimal_js__);
//Prestige by purchasing augmentation
function prestigeAugmentation() {
Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])();
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].prestigeAugmentation();
//Delete all Worker Scripts objects
Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])();
var homeComp = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getHomeComputer();
//Delete all servers except home computer
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["h" /* prestigeAllServers */])();
//Delete Special Server IPs
Object(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])(); //Must be done before initForeignServers()
//Reset home computer (only the programs) and add to AllServers
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["i" /* prestigeHomeComputer */])(homeComp);
if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink) &&
__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].Neurolink].owned) {
homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].FTPCrackProgram);
homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram);
}
if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot) &&
__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].CashRoot].owned) {
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].setMoney(new __WEBPACK_IMPORTED_MODULE_15__utils_decimal_js___default.a(1000000));
homeComp.programs.push(__WEBPACK_IMPORTED_MODULE_4__CreateProgram_js__["a" /* Programs */].BruteSSHProgram);
}
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["a" /* AddToAllServers */])(homeComp);
//Re-create foreign servers
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["f" /* initForeignServers */])();
//Darkweb is purchase-able
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button");
//Gain favor for Companies
for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) {
if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) {
__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].gainFavor();
}
}
//Gain favor for factions
for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) {
if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) {
__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].gainFavor();
}
}
//Stop a Terminal action if there is onerror
if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) {
__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false;
__WEBPACK_IMPORTED_MODULE_14__Terminal_js__["a" /* Terminal */].finishAction(true);
}
//Re-initialize things - This will update any changes
Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations
Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].reapplyAllSourceFiles();
Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])();
//Clear terminal
$("#terminal tr:not(:last)").remove();
Object(__WEBPACK_IMPORTED_MODULE_14__Terminal_js__["c" /* postNetburnerText */])();
//Messages
Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])();
//Reset Stock market
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].hasWseAccount) {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["d" /* initStockMarket */])();
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["f" /* initSymbolToStockMap */])();
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["h" /* setStockMarketContentCreated */])(false);
var stockMarketList = document.getElementById("stock-market-list");
while(stockMarketList.firstChild) {
stockMarketList.removeChild(stockMarketList.firstChild);
}
}
//Gang, in BitNode 2
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].inGang()) {
var faction = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].gang.facName];
if (faction instanceof __WEBPACK_IMPORTED_MODULE_6__Faction_js__["a" /* Faction */]) {
Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["h" /* joinFaction */])(faction);
}
}
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent();
//Red Pill
if (Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["f" /* augmentationExists */])(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill) &&
__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["b" /* AugmentationNames */].TheRedPill].owned) {
var WorldDaemon = __WEBPACK_IMPORTED_MODULE_11__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["b" /* SpecialServerNames */].WorldDaemon]];
var DaedalusServer = __WEBPACK_IMPORTED_MODULE_11__Server_js__["b" /* AllServers */][__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["a" /* SpecialServerIps */][__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["b" /* SpecialServerNames */].DaedalusServer]];
if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);
}
}
}
//Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile() {
Object(__WEBPACK_IMPORTED_MODULE_2__BitNode_js__["c" /* initBitNodeMultipliers */])();
//Crime statistics
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].prestigeSourceFile();
//Delete all Worker Scripts objects
Object(__WEBPACK_IMPORTED_MODULE_9__NetscriptWorker_js__["e" /* prestigeWorkerScripts */])();
var homeComp = __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].getHomeComputer();
//Delete all servers except home computer
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["h" /* prestigeAllServers */])(); //Must be done before initForeignServers()
//Delete Special Server IPs
Object(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["e" /* prestigeSpecialServerIps */])();
//Reset home computer (only the programs) and add to AllServers
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["i" /* prestigeHomeComputer */])(homeComp);
var srcFile1Owned = false;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].sourceFiles.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].sourceFiles[i].n == 1) {
srcFile1Owned = true;
}
}
if (srcFile1Owned) {
homeComp.setMaxRam(32);
} else {
homeComp.setMaxRam(8);
}
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["a" /* AddToAllServers */])(homeComp);
//Re-create foreign servers
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["f" /* initForeignServers */])();
//Darkweb is purchase-able
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button");
//Reset favor for Companies
for (var member in __WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */]) {
if (__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */].hasOwnProperty(member)) {
__WEBPACK_IMPORTED_MODULE_3__Company_js__["a" /* Companies */][member].favor = 0;
}
}
//Reset favor for factions
for (var member in __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */]) {
if (__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */].hasOwnProperty(member)) {
__WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][member].favor = 0;
}
}
//Stop a Terminal action if there is one
if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress) {
__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"]._actionInProgress = false;
__WEBPACK_IMPORTED_MODULE_14__Terminal_js__["a" /* Terminal */].finishAction(true);
}
//Delete all Augmentations
for (var name in __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */]) {
if (__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */].hasOwnProperty(name)) {
delete __WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["c" /* Augmentations */][name];
}
}
//Re-initialize things - This will update any changes
Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["f" /* initFactions */])(); //Factions must be initialized before augmentations
Object(__WEBPACK_IMPORTED_MODULE_1__Augmentations_js__["g" /* initAugmentations */])(); //Calls reapplyAllAugmentations() and resets Player multipliers
__WEBPACK_IMPORTED_MODULE_10__Player_js__["a" /* Player */].reapplyAllSourceFiles();
Object(__WEBPACK_IMPORTED_MODULE_3__Company_js__["h" /* initCompanies */])();
//Clear terminal
$("#terminal tr:not(:last)").remove();
Object(__WEBPACK_IMPORTED_MODULE_14__Terminal_js__["c" /* postNetburnerText */])();
//Messages
Object(__WEBPACK_IMPORTED_MODULE_8__Message_js__["d" /* initMessages */])();
var mainMenu = document.getElementById("mainmenu-container");
mainMenu.style.visibility = "visible";
__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].loadTerminalContent();
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 32 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export hacknetNodesInit */
/* unused harmony export HacknetNode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return purchaseHacknet; });
/* unused harmony export updateTotalHacknetProduction */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getCostOfNextHacknetNode; });
/* unused harmony export updateHacknetNodesMultiplierButtons */
/* unused harmony export getMaxNumberLevelUpgrades */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return displayHacknetNodesContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return updateHacknetNodesContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return processAllHacknetNodeEarnings; });
/* unused harmony export getHacknetNode */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* HacknetNode.js */
function hacknetNodesInit() {
var mult1x = document.getElementById("hacknet-nodes-1x-multiplier");
mult1x.addEventListener("click", function() {
hacknetNodePurchaseMultiplier = 1;
updateHacknetNodesMultiplierButtons();
updateHacknetNodesContent();
return false;
});
var mult5x = document.getElementById("hacknet-nodes-5x-multiplier");
mult5x.addEventListener("click", function() {
hacknetNodePurchaseMultiplier = 5;
updateHacknetNodesMultiplierButtons();
updateHacknetNodesContent();
return false;
});
var mult10x = document.getElementById("hacknet-nodes-10x-multiplier");
mult10x.addEventListener("click", function() {
hacknetNodePurchaseMultiplier = 10;
updateHacknetNodesMultiplierButtons();
updateHacknetNodesContent();
return false;
});
var multMax = document.getElementById("hacknet-nodes-max-multiplier");
multMax.addEventListener("click", function() {
hacknetNodePurchaseMultiplier = 0;
updateHacknetNodesMultiplierButtons();
updateHacknetNodesContent();
return false;
});
}
document.addEventListener("DOMContentLoaded", hacknetNodesInit, false);
function HacknetNode(name) {
this.level = 1;
this.ram = 1; //GB
this.cores = 1;
this.name = name;
this.totalMoneyGenerated = 0;
this.onlineTimeSeconds = 0;
this.moneyGainRatePerSecond = 0;
}
HacknetNode.prototype.updateMoneyGainRate = function() {
//How much extra $/s is gained per level
var gainPerLevel = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMoneyGainPerLevel;
this.moneyGainRatePerSecond = (this.level * gainPerLevel) *
Math.pow(1.035, this.ram-1) *
((this.cores + 5) / 6) *
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_money_mult *
__WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HacknetNodeMoney;
if (isNaN(this.moneyGainRatePerSecond)) {
this.moneyGainRatePerSecond = 0;
Object(__WEBPACK_IMPORTED_MODULE_5__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Error in calculating Hacknet Node production. Please report to game developer");
}
updateTotalHacknetProduction();
}
HacknetNode.prototype.calculateLevelUpgradeCost = function(levels=1) {
if (levels < 1) {return 0;}
var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeLevelMult;
var totalMultiplier = 0; //Summed
var currLevel = this.level;
for (var i = 0; i < levels; ++i) {
totalMultiplier += Math.pow(mult, currLevel);
++currLevel;
}
return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode / 2 * totalMultiplier * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_level_cost_mult;
}
//Wrapper function for Netscript
HacknetNode.prototype.getLevelUpgradeCost = function(levels=1) {
return this.calculateLevelUpgradeCost(levels);
}
HacknetNode.prototype.purchaseLevelUpgrade = function(levels=1) {
var cost = this.calculateLevelUpgradeCost(levels);
if (isNaN(cost)) {return false;}
if (this.level + levels > __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) {
var diff = Math.max(0, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - this.level);
return this.purchaseLevelUpgrade(diff);
}
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;}
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost);
this.level += levels;
this.updateMoneyGainRate();
return true;
}
//Wrapper function for Netscript
HacknetNode.prototype.upgradeLevel = function(levels=1) {
return this.purchaseLevelUpgrade(levels);
}
HacknetNode.prototype.calculateRamUpgradeCost = function() {
var numUpgrades = Math.log2(this.ram);
//Calculate cost
//Base cost of RAM is 50k per 1GB, increased by some multiplier for each time RAM is upgraded
var baseCost = this.ram * __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHacknetNode;
var mult = Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeRamMult, numUpgrades);
return baseCost * mult * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_ram_cost_mult;
}
//Wrapper function for Netscript
HacknetNode.prototype.getRamUpgradeCost = function() {
return this.calculateRamUpgradeCost();
}
HacknetNode.prototype.purchaseRamUpgrade = function() {
var cost = this.calculateRamUpgradeCost();
if (isNaN(cost)) {return false;}
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;}
if (this.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) {return false;}
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost);
this.ram *= 2; //Ram is always doubled
this.updateMoneyGainRate();
return true;
}
//Wrapper function for Netscript
HacknetNode.prototype.upgradeRam = function() {
return this.purchaseRamUpgrade();
}
HacknetNode.prototype.calculateCoreUpgradeCost = function() {
var coreBaseCost = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNodeCore;
var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeUpgradeCoreMult;
return coreBaseCost * Math.pow(mult, this.cores-1) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_core_cost_mult;
}
//Wrapper function for Netscript
HacknetNode.prototype.getCoreUpgradeCost = function() {
return this.calculateCoreUpgradeCost();
}
HacknetNode.prototype.purchaseCoreUpgrade = function() {
var cost = this.calculateCoreUpgradeCost();
if (isNaN(cost)) {return false;}
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {return false;}
if (this.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) {return false;}
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost);
++this.cores;
this.updateMoneyGainRate();
return true;
}
//Wrapper function for Netscript
HacknetNode.prototype.upgradeCore = function() {
return this.purchaseCoreUpgrade();
}
/* Saving and loading HackNets */
HacknetNode.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["b" /* Generic_toJSON */])("HacknetNode", this);
}
HacknetNode.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(HacknetNode, value.data);
}
__WEBPACK_IMPORTED_MODULE_7__utils_JSONReviver_js__["c" /* Reviver */].constructors.HacknetNode = HacknetNode;
function purchaseHacknet() {
/* INTERACTIVE TUTORIAL */
if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["b" /* iTutorialIsRunning */]) {
if (__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["a" /* currITutorialStep */] == __WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["e" /* iTutorialSteps */].HacknetNodesIntroduction) {
Object(__WEBPACK_IMPORTED_MODULE_3__InteractiveTutorial_js__["c" /* iTutorialNextStep */])();
} else {
return;
}
}
/* END INTERACTIVE TUTORIAL */
var cost = getCostOfNextHacknetNode();
if (isNaN(cost)) {throw new Error("Cost is NaN"); return;}
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {
//dialogBoxCreate("You cannot afford to purchase a Hacknet Node!");
return false;
}
//Auto generate a name for the node for now...TODO
var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length;
var name = "hacknet-node-" + numOwned;
var node = new HacknetNode(name);
node.updateMoneyGainRate();
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].loseMoney(cost);
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.push(node);
displayHacknetNodesContent();
updateTotalHacknetProduction();
return numOwned;
}
//Calculates the total production from all HacknetNodes
function updateTotalHacknetProduction() {
var total = 0;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) {
total += __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].moneyGainRatePerSecond;
}
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction = total;
}
function getCostOfNextHacknetNode() {
//Cost increases exponentially based on how many you own
var numOwned = __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length;
var mult = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodePurchaseNextMult;
return __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].BaseCostForHacknetNode * Math.pow(mult, numOwned) * __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknet_node_purchase_cost_mult;
}
var hacknetNodePurchaseMultiplier = 1;
function updateHacknetNodesMultiplierButtons() {
var mult1x = document.getElementById("hacknet-nodes-1x-multiplier");
var mult5x = document.getElementById("hacknet-nodes-5x-multiplier");
var mult10x = document.getElementById("hacknet-nodes-10x-multiplier");
var multMax = document.getElementById("hacknet-nodes-max-multiplier");
mult1x.setAttribute("class", "a-link-button");
mult5x.setAttribute("class", "a-link-button");
mult10x.setAttribute("class", "a-link-button");
multMax.setAttribute("class", "a-link-button");
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length == 0) {
mult1x.setAttribute("class", "a-link-button-inactive");
mult5x.setAttribute("class", "a-link-button-inactive");
mult10x.setAttribute("class", "a-link-button-inactive");
multMax.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 1) {
mult1x.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 5) {
mult5x.setAttribute("class", "a-link-button-inactive");
} else if (hacknetNodePurchaseMultiplier == 10) {
mult10x.setAttribute("class", "a-link-button-inactive");
} else {
multMax.setAttribute("class", "a-link-button-inactive");
}
}
//Calculate the maximum number of times the Player can afford to upgrade
//a Hacknet Node's level"
function getMaxNumberLevelUpgrades(nodeObj) {
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(1))) {return 0;}
var min = 1;
var max = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel-1;
var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level;
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(levelsToMax))) {
return levelsToMax;
}
while (min <= max) {
var curr = (min + max) / 2 | 0;
if (curr != __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel &&
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr)) &&
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr+1))) {
return Math.min(levelsToMax, curr);
} else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(nodeObj.calculateLevelUpgradeCost(curr))) {
max = curr - 1;
} else if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.gt(nodeObj.calculateLevelUpgradeCost(curr))) {
min = curr + 1;
} else {
return Math.min(levelsToMax, curr);
}
}
}
//Creates Hacknet Node DOM elements when the page is opened
function displayHacknetNodesContent() {
//Update Hacknet Nodes button
var newPurchaseButton = Object(__WEBPACK_IMPORTED_MODULE_6__utils_HelperFunctions_js__["b" /* clearEventListeners */])("hacknet-nodes-purchase-button");
newPurchaseButton.addEventListener("click", function() {
purchaseHacknet();
return false;
});
//Handle Purchase multiplier buttons
updateHacknetNodesMultiplierButtons();
//Remove all old hacknet Node DOM elements
var hacknetNodesList = document.getElementById("hacknet-nodes-list");
while (hacknetNodesList.firstChild) {
hacknetNodesList.removeChild(hacknetNodesList.firstChild);
}
//Then re-create them
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) {
createHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]);
}
updateHacknetNodesContent();
}
//Update information on all Hacknet Node DOM elements
function updateHacknetNodesContent() {
//Set purchase button to inactive if not enough money, and update its price display
var cost = getCostOfNextHacknetNode();
var purchaseButton = document.getElementById("hacknet-nodes-purchase-button");
purchaseButton.innerHTML = "Purchase Hacknet Node - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2);
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(cost)) {
purchaseButton.setAttribute("class", "a-link-button-inactive");
} else {
purchaseButton.setAttribute("class", "a-link-button");
}
//Update player's money
var moneyElem = document.getElementById("hacknet-nodes-money");
moneyElem.innerHTML = "Money: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.toNumber(), 2) + "<br>" +
"Total production from all Hacknet Nodes: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].totalHacknetNodeProduction, 2) + " / second";
//Update information in each owned hacknet node
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) {
updateHacknetNodeDomElement(__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]);
}
}
//Creates a single Hacknet Node DOM element
function createHacknetNodeDomElement(nodeObj) {
var nodeName = nodeObj.name;
var listItem = document.createElement("li");
listItem.setAttribute("class", "hacknet-node");
var span = document.createElement("span");
span.style.display = "inline";
var buttonDiv = document.createElement("div");
buttonDiv.setAttribute("class", "hacknet-node-button-div");
//Text
var txt = document.createElement("p");
//txt.setAttribute("id", "hacknet-node-text-" + nodeName);
txt.id = "hacknet-node-text-" + nodeName;
//Upgrade buttons
var upgradeLevelButton = document.createElement("a");
var upgradeRamButton = document.createElement("a");
var upgradeCoreButton = document.createElement("a");
//upgradeLevelButton.setAttribute("id", "hacknet-node-upgrade-level-" + nodeName);
upgradeLevelButton.id = "hacknet-node-upgrade-level-" + nodeName;
upgradeLevelButton.setAttribute("class", "a-link-button-inactive");
upgradeLevelButton.addEventListener("click", function() {
var numUpgrades = hacknetNodePurchaseMultiplier;
if (hacknetNodePurchaseMultiplier == 0) {
numUpgrades = getMaxNumberLevelUpgrades(nodeObj);
}
nodeObj.purchaseLevelUpgrade(numUpgrades);
updateHacknetNodesContent();
return false;
});
//upgradeRamButton.setAttribute("id", "hacknet-node-upgrade-ram-" + nodeName);
upgradeRamButton.id = "hacknet-node-upgrade-ram-" + nodeName;
upgradeRamButton.setAttribute("class", "a-link-button-inactive");
upgradeRamButton.addEventListener("click", function() {
nodeObj.purchaseRamUpgrade();
updateHacknetNodesContent();
return false;
});
//upgradeCoreButton.setAttribute("id", "hacknet-node-upgrade-core-" + nodeName);
upgradeCoreButton.id = "hacknet-node-upgrade-core-" + nodeName;
upgradeCoreButton.setAttribute("class", "a-link-button-inactive");
upgradeCoreButton.addEventListener("click", function() {
nodeObj.purchaseCoreUpgrade();
updateHacknetNodesContent();
return false;
});
//Put all the components together in the li element
span.appendChild(txt);
buttonDiv.appendChild(upgradeLevelButton);
buttonDiv.appendChild(upgradeRamButton);
buttonDiv.appendChild(upgradeCoreButton);
span.appendChild(buttonDiv);
listItem.appendChild(span);
document.getElementById("hacknet-nodes-list").appendChild(listItem);
//Set the text and stuff inside the DOM element
updateHacknetNodeDomElement(nodeObj);
}
//Updates information on a single hacknet node DOM element
function updateHacknetNodeDomElement(nodeObj) {
var nodeName = nodeObj.name;
var txt = document.getElementById("hacknet-node-text-" + nodeName);
if (txt == null) {throw new Error("Cannot find text element");}
txt.innerHTML = "Node name: " + nodeName + "<br>" +
"Production: $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.totalMoneyGenerated, 2) +
" ($" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(nodeObj.moneyGainRatePerSecond, 2) + " / second) <br>" +
"Level: " + nodeObj.level + "<br>" +
"RAM: " + nodeObj.ram + "GB<br>" +
"Cores: " + nodeObj.cores;
//Upgrade level
var upgradeLevelButton = document.getElementById("hacknet-node-upgrade-level-" + nodeName);
if (upgradeLevelButton == null) {throw new Error("Cannot find upgrade level button element");}
if (nodeObj.level >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel) {
upgradeLevelButton.innerHTML = "MAX LEVEL";
upgradeLevelButton.setAttribute("class", "a-link-button-inactive");
} else {
var multiplier = 0;
if (hacknetNodePurchaseMultiplier == 0) {
//Max
multiplier = getMaxNumberLevelUpgrades(nodeObj);
} else {
var levelsToMax = __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxLevel - nodeObj.level;
multiplier = Math.min(levelsToMax, hacknetNodePurchaseMultiplier);
}
var upgradeLevelCost = nodeObj.calculateLevelUpgradeCost(multiplier);
upgradeLevelButton.innerHTML = "Upgrade Hacknet Node Level x" + multiplier +
" - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeLevelCost, 2);
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeLevelCost)) {
upgradeLevelButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeLevelButton.setAttribute("class", "a-link-button");
}
}
//Upgrade RAM
var upgradeRamButton = document.getElementById("hacknet-node-upgrade-ram-" + nodeName);
if (upgradeRamButton == null) {throw new Error("Cannot find upgrade ram button element");}
if (nodeObj.ram >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxRam) {
upgradeRamButton.innerHTML = "MAX RAM";
upgradeRamButton.setAttribute("class", "a-link-button-inactive");
} else {
var upgradeRamCost = nodeObj.calculateRamUpgradeCost();
upgradeRamButton.innerHTML = "Upgrade Hacknet Node RAM -$" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeRamCost, 2);
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeRamCost)) {
upgradeRamButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeRamButton.setAttribute("class", "a-link-button");
}
}
//Upgrade Cores
var upgradeCoreButton = document.getElementById("hacknet-node-upgrade-core-" + nodeName);
if (upgradeCoreButton == null) {throw new Error("Cannot find upgrade cores button element");}
if (nodeObj.cores >= __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].HacknetNodeMaxCores) {
upgradeCoreButton.innerHTML = "MAX CORES";
upgradeCoreButton.setAttribute("class", "a-link-button-inactive");
} else {
var upgradeCoreCost = nodeObj.calculateCoreUpgradeCost();
upgradeCoreButton.innerHTML = "Purchase additional CPU Core - $" + Object(__WEBPACK_IMPORTED_MODULE_8__utils_StringHelperFunctions_js__["c" /* formatNumber */])(upgradeCoreCost, 2);
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].money.lt(upgradeCoreCost)) {
upgradeCoreButton.setAttribute("class", "a-link-button-inactive");
} else {
upgradeCoreButton.setAttribute("class", "a-link-button");
}
}
}
function processAllHacknetNodeEarnings(numCycles) {
var total = 0;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) {
total += processSingleHacknetNodeEarnings(numCycles, __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i]);
}
return total;
}
function processSingleHacknetNodeEarnings(numCycles, nodeObj) {
var cyclesPerSecond = 1000 / __WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed;
var earningPerCycle = nodeObj.moneyGainRatePerSecond / cyclesPerSecond;
if (isNaN(earningPerCycle)) {throw new Error("Calculated Earnings is not a number");}
var totalEarnings = numCycles * earningPerCycle;
nodeObj.totalMoneyGenerated += totalEarnings;
nodeObj.onlineTimeSeconds += (numCycles * (__WEBPACK_IMPORTED_MODULE_2__engine_js__["Engine"]._idleSpeed / 1000));
__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].gainMoney(totalEarnings);
return totalEarnings;
}
function getHacknetNode(name) {
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i].name == name) {
return __WEBPACK_IMPORTED_MODULE_4__Player_js__["a" /* Player */].hacknetNodes[i];
}
}
return null;
}
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
/**
* Define a module along with a payload
* @param module a name for the payload
* @param payload a function to call with (acequire, exports, module) params
*/
(function() {
var ACE_NAMESPACE = "ace";
var global = (function() { return this; })();
if (!global && typeof window != "undefined") global = window; // strict mode
if (!ACE_NAMESPACE && typeof acequirejs !== "undefined")
return;
var define = function(module, deps, payload) {
if (typeof module !== "string") {
if (define.original)
define.original.apply(this, arguments);
else {
console.error("dropping module because define wasn\'t a string.");
console.trace();
}
return;
}
if (arguments.length == 2)
payload = deps;
if (!define.modules[module]) {
define.payloads[module] = payload;
define.modules[module] = null;
}
};
define.modules = {};
define.payloads = {};
/**
* Get at functionality define()ed using the function above
*/
var _acequire = function(parentId, module, callback) {
if (typeof module === "string") {
var payload = lookup(parentId, module);
if (payload != undefined) {
callback && callback();
return payload;
}
} else if (Object.prototype.toString.call(module) === "[object Array]") {
var params = [];
for (var i = 0, l = module.length; i < l; ++i) {
var dep = lookup(parentId, module[i]);
if (dep == undefined && acequire.original)
return;
params.push(dep);
}
return callback && callback.apply(null, params) || true;
}
};
var acequire = function(module, callback) {
var packagedModule = _acequire("", module, callback);
if (packagedModule == undefined && acequire.original)
return acequire.original.apply(this, arguments);
return packagedModule;
};
var normalizeModule = function(parentId, moduleName) {
// normalize plugin acequires
if (moduleName.indexOf("!") !== -1) {
var chunks = moduleName.split("!");
return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
}
// normalize relative acequires
if (moduleName.charAt(0) == ".") {
var base = parentId.split("/").slice(0, -1).join("/");
moduleName = base + "/" + moduleName;
while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
var previous = moduleName;
moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
}
}
return moduleName;
};
/**
* Internal function to lookup moduleNames and resolve them by calling the
* definition function if needed.
*/
var lookup = function(parentId, moduleName) {
moduleName = normalizeModule(parentId, moduleName);
var module = define.modules[moduleName];
if (!module) {
module = define.payloads[moduleName];
if (typeof module === 'function') {
var exports = {};
var mod = {
id: moduleName,
uri: '',
exports: exports,
packaged: true
};
var req = function(module, callback) {
return _acequire(moduleName, module, callback);
};
var returnValue = module(req, exports, mod);
exports = returnValue || mod.exports;
define.modules[moduleName] = exports;
delete define.payloads[moduleName];
}
module = define.modules[moduleName] = exports || module;
}
return module;
};
function exportAce(ns) {
var root = global;
if (ns) {
if (!global[ns])
global[ns] = {};
root = global[ns];
}
if (!root.define || !root.define.packaged) {
define.original = root.define;
root.define = define;
root.define.packaged = true;
}
if (!root.acequire || !root.acequire.packaged) {
acequire.original = root.acequire;
root.acequire = acequire;
root.acequire.packaged = true;
}
}
exportAce(ACE_NAMESPACE);
})();
ace.define("ace/lib/regexp",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var real = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split
},
compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
compliantLastIndexIncrement = function () {
var x = /^/g;
real.test.call(x, "");
return !x.lastIndex;
}();
if (compliantLastIndexIncrement && compliantExecNpcg)
return;
RegExp.prototype.exec = function (str) {
var match = real.exec.apply(this, arguments),
name, r2;
if ( typeof(str) == 'string' && match) {
if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
real.replace.call(str.slice(match.index), r2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined)
match[i] = undefined;
}
});
}
if (this._xregexp && this._xregexp.captureNames) {
for (var i = 1; i < match.length; i++) {
name = this._xregexp.captureNames[i - 1];
if (name)
match[name] = match[i];
}
}
if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
}
return match;
};
if (!compliantLastIndexIncrement) {
RegExp.prototype.test = function (str) {
var match = real.exec.call(this, str);
if (match && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
return !!match;
};
}
function getNativeFlags (regex) {
return (regex.global ? "g" : "") +
(regex.ignoreCase ? "i" : "") +
(regex.multiline ? "m" : "") +
(regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
(regex.sticky ? "y" : "");
}
function indexOf (array, item, from) {
if (Array.prototype.indexOf) // Use the native array method if available
return array.indexOf(item, from);
for (var i = from || 0; i < array.length; i++) {
if (array[i] === item)
return i;
}
return -1;
}
});
ace.define("ace/lib/es5-shim",["require","exports","module"], function(acequire, exports, module) {
function Empty() {}
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
var target = this;
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
var args = slice.call(arguments, 1); // for normal call
var bound = function () {
if (this instanceof bound) {
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
if(target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
}
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
var _toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
if ([1,2].splice(0).length != 2) {
if(function() { // test IE < 9 to splice bug - see issue #138
function makeArray(l) {
var a = new Array(l+2);
a[0] = a[1] = 0;
return a;
}
var array = [], lengthBefore;
array.splice.apply(array, makeArray(20));
array.splice.apply(array, makeArray(26));
lengthBefore = array.length; //46
array.splice(5, 0, "XXX"); // add one element
lengthBefore + 1 == array.length
if (lengthBefore + 1 == array.length) {
return true;// has right splice implementation without bugs
}
}()) {//IE 6/7
var array_splice = Array.prototype.splice;
Array.prototype.splice = function(start, deleteCount) {
if (!arguments.length) {
return [];
} else {
return array_splice.apply(this, [
start === void 0 ? 0 : start,
deleteCount === void 0 ? (this.length - start) : deleteCount
].concat(slice.call(arguments, 2)))
}
};
} else {//IE8
Array.prototype.splice = function(pos, removeCount){
var length = this.length;
if (pos > 0) {
if (pos > length)
pos = length;
} else if (pos == void 0) {
pos = 0;
} else if (pos < 0) {
pos = Math.max(length + pos, 0);
}
if (!(pos+removeCount < length))
removeCount = length - pos;
var removed = this.slice(pos, pos+removeCount);
var insert = slice.call(arguments, 2);
var add = insert.length;
if (pos === length) {
if (add) {
this.push.apply(this, insert);
}
} else {
var remove = Math.min(removeCount, length - pos);
var tailOldPos = pos + remove;
var tailNewPos = tailOldPos + add - remove;
var tailCount = length - tailOldPos;
var lengthAfterRemove = length - remove;
if (tailNewPos < tailOldPos) { // case A
for (var i = 0; i < tailCount; ++i) {
this[tailNewPos+i] = this[tailOldPos+i];
}
} else if (tailNewPos > tailOldPos) { // case B
for (i = tailCount; i--; ) {
this[tailNewPos+i] = this[tailOldPos+i];
}
} // else, add == remove (nothing to do)
if (add && pos === lengthAfterRemove) {
this.length = lengthAfterRemove; // truncate array
this.push.apply(this, insert);
} else {
this.length = lengthAfterRemove + add; // reserves space
for (i = 0; i < add; ++i) {
this[pos+i] = insert[i];
}
}
}
return removed;
};
}
}
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return _toString(obj) == "[object Array]";
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
fun.call(thisp, self[i], i, object);
}
}
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
}
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
if (!length && arguments.length == 1) {
throw new TypeError("reduce of empty array with no initial value");
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
if (++i >= length) {
throw new TypeError("reduce of empty array with no initial value");
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
if (!length && arguments.length == 1) {
throw new TypeError("reduceRight of empty array with no initial value");
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
if (--i < 0) {
throw new TypeError("reduceRight of empty array with no initial value");
}
} while (true);
}
do {
if (i in this) {
result = fun.call(void 0, result, self[i], i, object);
}
} while (i--);
return result;
};
}
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
if (!Object.getPrototypeOf) {
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor ?
object.constructor.prototype :
prototypeOfObject
);
};
}
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
if (!owns(object, property))
return;
var descriptor, getter, setter;
descriptor = { enumerable: true, configurable: true };
if (supportsAccessors) {
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
return descriptor;
}
}
descriptor.value = object[property];
return descriptor;
};
}
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
if (!Object.create) {
var createEmpty;
if (Object.prototype.__proto__ === null) {
createEmpty = function () {
return { "__proto__": null };
};
} else {
createEmpty = function () {
var empty = {};
for (var i in empty)
empty[i] = null;
empty.constructor =
empty.hasOwnProperty =
empty.propertyIsEnumerable =
empty.isPrototypeOf =
empty.toLocaleString =
empty.toString =
empty.valueOf =
empty.__proto__ = null;
return empty;
}
}
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = createEmpty();
} else {
if (typeof prototype != "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
object.__proto__ = prototype;
}
if (properties !== void 0)
Object.defineProperties(object, properties);
return object;
};
}
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
}
}
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
}
}
if (owns(descriptor, "value")) {
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
delete object[property];
object[property] = descriptor.value;
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
if (!Object.seal) {
Object.seal = function seal(object) {
return object;
};
}
if (!Object.freeze) {
Object.freeze = function freeze(object) {
return object;
};
}
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
return object;
};
}
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
if (Object(object) === object) {
throw new TypeError(); // TODO message
}
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if (
(typeof object != "object" && typeof object != "function") ||
object === null
) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
function toInteger(n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
}
function isPrimitive(input) {
var type = typeof input;
return (
input === null ||
type === "undefined" ||
type === "boolean" ||
type === "number" ||
type === "string"
);
}
function toPrimitive(input) {
var val, valueOf, toString;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (typeof valueOf === "function") {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toString = input.toString;
if (typeof toString === "function") {
val = toString.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
}
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
return Object(o);
};
});
ace.define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"], function(acequire, exports, module) {
"use strict";
acequire("./regexp");
acequire("./es5-shim");
});
ace.define("ace/lib/dom",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var XHTML_NS = "http://www.w3.org/1999/xhtml";
exports.getDocumentHead = function(doc) {
if (!doc)
doc = document;
return doc.head || doc.getElementsByTagName("head")[0] || doc.documentElement;
}
exports.createElement = function(tag, ns) {
return document.createElementNS ?
document.createElementNS(ns || XHTML_NS, tag) :
document.createElement(tag);
};
exports.hasCssClass = function(el, name) {
var classes = (el.className + "").split(/\s+/g);
return classes.indexOf(name) !== -1;
};
exports.addCssClass = function(el, name) {
if (!exports.hasCssClass(el, name)) {
el.className += " " + name;
}
};
exports.removeCssClass = function(el, name) {
var classes = el.className.split(/\s+/g);
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
classes.splice(index, 1);
}
el.className = classes.join(" ");
};
exports.toggleCssClass = function(el, name) {
var classes = el.className.split(/\s+/g), add = true;
while (true) {
var index = classes.indexOf(name);
if (index == -1) {
break;
}
add = false;
classes.splice(index, 1);
}
if (add)
classes.push(name);
el.className = classes.join(" ");
return add;
};
exports.setCssClass = function(node, className, include) {
if (include) {
exports.addCssClass(node, className);
} else {
exports.removeCssClass(node, className);
}
};
exports.hasCssString = function(id, doc) {
var index = 0, sheets;
doc = doc || document;
if (doc.createStyleSheet && (sheets = doc.styleSheets)) {
while (index < sheets.length)
if (sheets[index++].owningElement.id === id) return true;
} else if ((sheets = doc.getElementsByTagName("style"))) {
while (index < sheets.length)
if (sheets[index++].id === id) return true;
}
return false;
};
exports.importCssString = function importCssString(cssText, id, doc) {
doc = doc || document;
if (id && exports.hasCssString(id, doc))
return null;
var style;
if (id)
cssText += "\n/*# sourceURL=ace/css/" + id + " */";
if (doc.createStyleSheet) {
style = doc.createStyleSheet();
style.cssText = cssText;
if (id)
style.owningElement.id = id;
} else {
style = exports.createElement("style");
style.appendChild(doc.createTextNode(cssText));
if (id)
style.id = id;
exports.getDocumentHead(doc).appendChild(style);
}
};
exports.importCssStylsheet = function(uri, doc) {
if (doc.createStyleSheet) {
doc.createStyleSheet(uri);
} else {
var link = exports.createElement('link');
link.rel = 'stylesheet';
link.href = uri;
exports.getDocumentHead(doc).appendChild(link);
}
};
exports.getInnerWidth = function(element) {
return (
parseInt(exports.computedStyle(element, "paddingLeft"), 10) +
parseInt(exports.computedStyle(element, "paddingRight"), 10) +
element.clientWidth
);
};
exports.getInnerHeight = function(element) {
return (
parseInt(exports.computedStyle(element, "paddingTop"), 10) +
parseInt(exports.computedStyle(element, "paddingBottom"), 10) +
element.clientHeight
);
};
exports.scrollbarWidth = function(document) {
var inner = exports.createElement("ace_inner");
inner.style.width = "100%";
inner.style.minWidth = "0px";
inner.style.height = "200px";
inner.style.display = "block";
var outer = exports.createElement("ace_outer");
var style = outer.style;
style.position = "absolute";
style.left = "-10000px";
style.overflow = "hidden";
style.width = "200px";
style.minWidth = "0px";
style.height = "150px";
style.display = "block";
outer.appendChild(inner);
var body = document.documentElement;
body.appendChild(outer);
var noScrollbar = inner.offsetWidth;
style.overflow = "scroll";
var withScrollbar = inner.offsetWidth;
if (noScrollbar == withScrollbar) {
withScrollbar = outer.clientWidth;
}
body.removeChild(outer);
return noScrollbar-withScrollbar;
};
if (typeof document == "undefined") {
exports.importCssString = function() {};
return;
}
if (window.pageYOffset !== undefined) {
exports.getPageScrollTop = function() {
return window.pageYOffset;
};
exports.getPageScrollLeft = function() {
return window.pageXOffset;
};
}
else {
exports.getPageScrollTop = function() {
return document.body.scrollTop;
};
exports.getPageScrollLeft = function() {
return document.body.scrollLeft;
};
}
if (window.getComputedStyle)
exports.computedStyle = function(element, style) {
if (style)
return (window.getComputedStyle(element, "") || {})[style] || "";
return window.getComputedStyle(element, "") || {};
};
else
exports.computedStyle = function(element, style) {
if (style)
return element.currentStyle[style];
return element.currentStyle;
};
exports.setInnerHtml = function(el, innerHtml) {
var element = el.cloneNode(false);//document.createElement("div");
element.innerHTML = innerHtml;
el.parentNode.replaceChild(element, el);
return element;
};
if ("textContent" in document.documentElement) {
exports.setInnerText = function(el, innerText) {
el.textContent = innerText;
};
exports.getInnerText = function(el) {
return el.textContent;
};
}
else {
exports.setInnerText = function(el, innerText) {
el.innerText = innerText;
};
exports.getInnerText = function(el) {
return el.innerText;
};
}
exports.getParentWindow = function(document) {
return document.defaultView || document.parentWindow;
};
});
ace.define("ace/lib/oop",["require","exports","module"], function(acequire, exports, module) {
"use strict";
exports.inherits = function(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
return obj;
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
ace.define("ace/lib/keys",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop"], function(acequire, exports, module) {
"use strict";
acequire("./fixoldbrowsers");
var oop = acequire("./oop");
var Keys = (function() {
var ret = {
MODIFIER_KEYS: {
16: 'Shift', 17: 'Ctrl', 18: 'Alt', 224: 'Meta'
},
KEY_MODS: {
"ctrl": 1, "alt": 2, "option" : 2, "shift": 4,
"super": 8, "meta": 8, "command": 8, "cmd": 8
},
FUNCTION_KEYS : {
8 : "Backspace",
9 : "Tab",
13 : "Return",
19 : "Pause",
27 : "Esc",
32 : "Space",
33 : "PageUp",
34 : "PageDown",
35 : "End",
36 : "Home",
37 : "Left",
38 : "Up",
39 : "Right",
40 : "Down",
44 : "Print",
45 : "Insert",
46 : "Delete",
96 : "Numpad0",
97 : "Numpad1",
98 : "Numpad2",
99 : "Numpad3",
100: "Numpad4",
101: "Numpad5",
102: "Numpad6",
103: "Numpad7",
104: "Numpad8",
105: "Numpad9",
'-13': "NumpadEnter",
112: "F1",
113: "F2",
114: "F3",
115: "F4",
116: "F5",
117: "F6",
118: "F7",
119: "F8",
120: "F9",
121: "F10",
122: "F11",
123: "F12",
144: "Numlock",
145: "Scrolllock"
},
PRINTABLE_KEYS: {
32: ' ', 48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5',
54: '6', 55: '7', 56: '8', 57: '9', 59: ';', 61: '=', 65: 'a',
66: 'b', 67: 'c', 68: 'd', 69: 'e', 70: 'f', 71: 'g', 72: 'h',
73: 'i', 74: 'j', 75: 'k', 76: 'l', 77: 'm', 78: 'n', 79: 'o',
80: 'p', 81: 'q', 82: 'r', 83: 's', 84: 't', 85: 'u', 86: 'v',
87: 'w', 88: 'x', 89: 'y', 90: 'z', 107: '+', 109: '-', 110: '.',
186: ';', 187: '=', 188: ',', 189: '-', 190: '.', 191: '/', 192: '`',
219: '[', 220: '\\',221: ']', 222: "'", 111: '/', 106: '*'
}
};
var name, i;
for (i in ret.FUNCTION_KEYS) {
name = ret.FUNCTION_KEYS[i].toLowerCase();
ret[name] = parseInt(i, 10);
}
for (i in ret.PRINTABLE_KEYS) {
name = ret.PRINTABLE_KEYS[i].toLowerCase();
ret[name] = parseInt(i, 10);
}
oop.mixin(ret, ret.MODIFIER_KEYS);
oop.mixin(ret, ret.PRINTABLE_KEYS);
oop.mixin(ret, ret.FUNCTION_KEYS);
ret.enter = ret["return"];
ret.escape = ret.esc;
ret.del = ret["delete"];
ret[173] = '-';
(function() {
var mods = ["cmd", "ctrl", "alt", "shift"];
for (var i = Math.pow(2, mods.length); i--;) {
ret.KEY_MODS[i] = mods.filter(function(x) {
return i & ret.KEY_MODS[x];
}).join("-") + "-";
}
})();
ret.KEY_MODS[0] = "";
ret.KEY_MODS[-1] = "input-";
return ret;
})();
oop.mixin(exports, Keys);
exports.keyCodeToString = function(keyCode) {
var keyString = Keys[keyCode];
if (typeof keyString != "string")
keyString = String.fromCharCode(keyCode);
return keyString.toLowerCase();
};
});
ace.define("ace/lib/useragent",["require","exports","module"], function(acequire, exports, module) {
"use strict";
exports.OS = {
LINUX: "LINUX",
MAC: "MAC",
WINDOWS: "WINDOWS"
};
exports.getOS = function() {
if (exports.isMac) {
return exports.OS.MAC;
} else if (exports.isLinux) {
return exports.OS.LINUX;
} else {
return exports.OS.WINDOWS;
}
};
if (typeof navigator != "object")
return;
var os = (navigator.platform.match(/mac|win|linux/i) || ["other"])[0].toLowerCase();
var ua = navigator.userAgent;
exports.isWin = (os == "win");
exports.isMac = (os == "mac");
exports.isLinux = (os == "linux");
exports.isIE =
(navigator.appName == "Microsoft Internet Explorer" || navigator.appName.indexOf("MSAppHost") >= 0)
? parseFloat((ua.match(/(?:MSIE |Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1])
: parseFloat((ua.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:)([0-9]+[\.0-9]+)/)||[])[1]); // for ie
exports.isOldIE = exports.isIE && exports.isIE < 9;
exports.isGecko = exports.isMozilla = (window.Controllers || window.controllers) && window.navigator.product === "Gecko";
exports.isOldGecko = exports.isGecko && parseInt((ua.match(/rv:(\d+)/)||[])[1], 10) < 4;
exports.isOpera = window.opera && Object.prototype.toString.call(window.opera) == "[object Opera]";
exports.isWebKit = parseFloat(ua.split("WebKit/")[1]) || undefined;
exports.isChrome = parseFloat(ua.split(" Chrome/")[1]) || undefined;
exports.isAIR = ua.indexOf("AdobeAIR") >= 0;
exports.isIPad = ua.indexOf("iPad") >= 0;
exports.isTouchPad = ua.indexOf("TouchPad") >= 0;
exports.isChromeOS = ua.indexOf(" CrOS ") >= 0;
});
ace.define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) {
"use strict";
var keys = acequire("./keys");
var useragent = acequire("./useragent");
var pressedKeys = null;
var ts = 0;
exports.addListener = function(elem, type, callback) {
if (elem.addEventListener) {
return elem.addEventListener(type, callback, false);
}
if (elem.attachEvent) {
var wrapper = function() {
callback.call(elem, window.event);
};
callback._wrapper = wrapper;
elem.attachEvent("on" + type, wrapper);
}
};
exports.removeListener = function(elem, type, callback) {
if (elem.removeEventListener) {
return elem.removeEventListener(type, callback, false);
}
if (elem.detachEvent) {
elem.detachEvent("on" + type, callback._wrapper || callback);
}
};
exports.stopEvent = function(e) {
exports.stopPropagation(e);
exports.preventDefault(e);
return false;
};
exports.stopPropagation = function(e) {
if (e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
};
exports.preventDefault = function(e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
};
exports.getButton = function(e) {
if (e.type == "dblclick")
return 0;
if (e.type == "contextmenu" || (useragent.isMac && (e.ctrlKey && !e.altKey && !e.shiftKey)))
return 2;
if (e.preventDefault) {
return e.button;
}
else {
return {1:0, 2:2, 4:1}[e.button];
}
};
exports.capture = function(el, eventHandler, releaseCaptureHandler) {
function onMouseUp(e) {
eventHandler && eventHandler(e);
releaseCaptureHandler && releaseCaptureHandler(e);
exports.removeListener(document, "mousemove", eventHandler, true);
exports.removeListener(document, "mouseup", onMouseUp, true);
exports.removeListener(document, "dragstart", onMouseUp, true);
}
exports.addListener(document, "mousemove", eventHandler, true);
exports.addListener(document, "mouseup", onMouseUp, true);
exports.addListener(document, "dragstart", onMouseUp, true);
return onMouseUp;
};
exports.addTouchMoveListener = function (el, callback) {
if ("ontouchmove" in el) {
var startx, starty;
exports.addListener(el, "touchstart", function (e) {
var touchObj = e.changedTouches[0];
startx = touchObj.clientX;
starty = touchObj.clientY;
});
exports.addListener(el, "touchmove", function (e) {
var factor = 1,
touchObj = e.changedTouches[0];
e.wheelX = -(touchObj.clientX - startx) / factor;
e.wheelY = -(touchObj.clientY - starty) / factor;
startx = touchObj.clientX;
starty = touchObj.clientY;
callback(e);
});
}
};
exports.addMouseWheelListener = function(el, callback) {
if ("onmousewheel" in el) {
exports.addListener(el, "mousewheel", function(e) {
var factor = 8;
if (e.wheelDeltaX !== undefined) {
e.wheelX = -e.wheelDeltaX / factor;
e.wheelY = -e.wheelDeltaY / factor;
} else {
e.wheelX = 0;
e.wheelY = -e.wheelDelta / factor;
}
callback(e);
});
} else if ("onwheel" in el) {
exports.addListener(el, "wheel", function(e) {
var factor = 0.35;
switch (e.deltaMode) {
case e.DOM_DELTA_PIXEL:
e.wheelX = e.deltaX * factor || 0;
e.wheelY = e.deltaY * factor || 0;
break;
case e.DOM_DELTA_LINE:
case e.DOM_DELTA_PAGE:
e.wheelX = (e.deltaX || 0) * 5;
e.wheelY = (e.deltaY || 0) * 5;
break;
}
callback(e);
});
} else {
exports.addListener(el, "DOMMouseScroll", function(e) {
if (e.axis && e.axis == e.HORIZONTAL_AXIS) {
e.wheelX = (e.detail || 0) * 5;
e.wheelY = 0;
} else {
e.wheelX = 0;
e.wheelY = (e.detail || 0) * 5;
}
callback(e);
});
}
};
exports.addMultiMouseDownListener = function(elements, timeouts, eventHandler, callbackName) {
var clicks = 0;
var startX, startY, timer;
var eventNames = {
2: "dblclick",
3: "tripleclick",
4: "quadclick"
};
function onMousedown(e) {
if (exports.getButton(e) !== 0) {
clicks = 0;
} else if (e.detail > 1) {
clicks++;
if (clicks > 4)
clicks = 1;
} else {
clicks = 1;
}
if (useragent.isIE) {
var isNewClick = Math.abs(e.clientX - startX) > 5 || Math.abs(e.clientY - startY) > 5;
if (!timer || isNewClick)
clicks = 1;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
if (clicks == 1) {
startX = e.clientX;
startY = e.clientY;
}
}
e._clicks = clicks;
eventHandler[callbackName]("mousedown", e);
if (clicks > 4)
clicks = 0;
else if (clicks > 1)
return eventHandler[callbackName](eventNames[clicks], e);
}
function onDblclick(e) {
clicks = 2;
if (timer)
clearTimeout(timer);
timer = setTimeout(function() {timer = null}, timeouts[clicks - 1] || 600);
eventHandler[callbackName]("mousedown", e);
eventHandler[callbackName](eventNames[clicks], e);
}
if (!Array.isArray(elements))
elements = [elements];
elements.forEach(function(el) {
exports.addListener(el, "mousedown", onMousedown);
if (useragent.isOldIE)
exports.addListener(el, "dblclick", onDblclick);
});
};
var getModifierHash = useragent.isMac && useragent.isOpera && !("KeyboardEvent" in window)
? function(e) {
return 0 | (e.metaKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.ctrlKey ? 8 : 0);
}
: function(e) {
return 0 | (e.ctrlKey ? 1 : 0) | (e.altKey ? 2 : 0) | (e.shiftKey ? 4 : 0) | (e.metaKey ? 8 : 0);
};
exports.getModifierString = function(e) {
return keys.KEY_MODS[getModifierHash(e)];
};
function normalizeCommandKeys(callback, e, keyCode) {
var hashId = getModifierHash(e);
if (!useragent.isMac && pressedKeys) {
if (e.getModifierState && (e.getModifierState("OS") || e.getModifierState("Win")))
hashId |= 8;
if (pressedKeys.altGr) {
if ((3 & hashId) != 3)
pressedKeys.altGr = 0;
else
return;
}
if (keyCode === 18 || keyCode === 17) {
var location = "location" in e ? e.location : e.keyLocation;
if (keyCode === 17 && location === 1) {
if (pressedKeys[keyCode] == 1)
ts = e.timeStamp;
} else if (keyCode === 18 && hashId === 3 && location === 2) {
var dt = e.timeStamp - ts;
if (dt < 50)
pressedKeys.altGr = true;
}
}
}
if (keyCode in keys.MODIFIER_KEYS) {
keyCode = -1;
}
if (hashId & 8 && (keyCode >= 91 && keyCode <= 93)) {
keyCode = -1;
}
if (!hashId && keyCode === 13) {
var location = "location" in e ? e.location : e.keyLocation;
if (location === 3) {
callback(e, hashId, -keyCode);
if (e.defaultPrevented)
return;
}
}
if (useragent.isChromeOS && hashId & 8) {
callback(e, hashId, keyCode);
if (e.defaultPrevented)
return;
else
hashId &= ~8;
}
if (!hashId && !(keyCode in keys.FUNCTION_KEYS) && !(keyCode in keys.PRINTABLE_KEYS)) {
return false;
}
return callback(e, hashId, keyCode);
}
exports.addCommandKeyListener = function(el, callback) {
var addListener = exports.addListener;
if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) {
var lastKeyDownKeyCode = null;
addListener(el, "keydown", function(e) {
lastKeyDownKeyCode = e.keyCode;
});
addListener(el, "keypress", function(e) {
return normalizeCommandKeys(callback, e, lastKeyDownKeyCode);
});
} else {
var lastDefaultPrevented = null;
addListener(el, "keydown", function(e) {
pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1;
var result = normalizeCommandKeys(callback, e, e.keyCode);
lastDefaultPrevented = e.defaultPrevented;
return result;
});
addListener(el, "keypress", function(e) {
if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) {
exports.stopEvent(e);
lastDefaultPrevented = null;
}
});
addListener(el, "keyup", function(e) {
pressedKeys[e.keyCode] = null;
});
if (!pressedKeys) {
resetPressedKeys();
addListener(window, "focus", resetPressedKeys);
}
}
};
function resetPressedKeys() {
pressedKeys = Object.create(null);
}
if (typeof window == "object" && window.postMessage && !useragent.isOldIE) {
var postMessageId = 1;
exports.nextTick = function(callback, win) {
win = win || window;
var messageName = "zero-timeout-message-" + postMessageId;
exports.addListener(win, "message", function listener(e) {
if (e.data == messageName) {
exports.stopPropagation(e);
exports.removeListener(win, "message", listener);
callback();
}
});
win.postMessage(messageName, "*");
};
}
exports.nextFrame = typeof window == "object" && (window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| window.oRequestAnimationFrame);
if (exports.nextFrame)
exports.nextFrame = exports.nextFrame.bind(window);
else
exports.nextFrame = function(callback) {
setTimeout(callback, 17);
};
});
ace.define("ace/lib/lang",["require","exports","module"], function(acequire, exports, module) {
"use strict";
exports.last = function(a) {
return a[a.length - 1];
};
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
var result = '';
while (count > 0) {
if (count & 1)
result += string;
if (count >>= 1)
string += string;
}
return result;
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '');
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (var i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject(array[i]);
else
copy[i] = array[i];
}
return copy;
};
exports.deepCopy = function deepCopy(obj) {
if (typeof obj !== "object" || !obj)
return obj;
var copy;
if (Array.isArray(obj)) {
copy = [];
for (var key = 0; key < obj.length; key++) {
copy[key] = deepCopy(obj[key]);
}
return copy;
}
if (Object.prototype.toString.call(obj) !== "[object Object]")
return obj;
copy = {};
for (var key in obj)
copy[key] = deepCopy(obj[key]);
return copy;
};
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
exports.createMap = function(props) {
var map = Object.create(null);
for (var i in props) {
map[i] = props[i];
}
return map;
};
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.escapeHTML = function(str) {
return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;");
};
exports.getMatchOffsets = function(string, regExp) {
var matches = [];
string.replace(regExp, function(str) {
matches.push({
offset: arguments[arguments.length-2],
length: str.length
});
});
return matches;
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
deferred.cancel();
timer = setTimeout(callback, timeout || 0);
return deferred;
};
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
deferred.isPending = function() {
return timer;
};
return deferred;
};
exports.delayedCall = function(fcn, defaultTimeout) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var _self = function(timeout) {
if (timer == null)
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.delay = function(timeout) {
timer && clearTimeout(timer);
timer = setTimeout(callback, timeout || defaultTimeout);
};
_self.schedule = _self;
_self.call = function() {
this.cancel();
fcn();
};
_self.cancel = function() {
timer && clearTimeout(timer);
timer = null;
};
_self.isPending = function() {
return timer;
};
return _self;
};
});
ace.define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang"], function(acequire, exports, module) {
"use strict";
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
var dom = acequire("../lib/dom");
var lang = acequire("../lib/lang");
var BROKEN_SETDATA = useragent.isChrome < 18;
var USE_IE_MIME_TYPE = useragent.isIE;
var TextInput = function(parentNode, host) {
var text = dom.createElement("textarea");
text.className = "ace_text-input";
if (useragent.isTouchPad)
text.setAttribute("x-palm-disable-auto-cap", true);
text.setAttribute("wrap", "off");
text.setAttribute("autocorrect", "off");
text.setAttribute("autocapitalize", "off");
text.setAttribute("spellcheck", false);
text.style.opacity = "0";
if (useragent.isOldIE) text.style.top = "-1000px";
parentNode.insertBefore(text, parentNode.firstChild);
var PLACEHOLDER = "\x01\x01";
var copied = false;
var pasted = false;
var inComposition = false;
var tempStyle = '';
var isSelectionEmpty = true;
try { var isFocused = document.activeElement === text; } catch(e) {}
event.addListener(text, "blur", function(e) {
host.onBlur(e);
isFocused = false;
});
event.addListener(text, "focus", function(e) {
isFocused = true;
host.onFocus(e);
resetSelection();
});
this.focus = function() {
if (tempStyle) return text.focus();
var top = text.style.top;
text.style.position = "fixed";
text.style.top = "0px";
text.focus();
setTimeout(function() {
text.style.position = "";
if (text.style.top == "0px")
text.style.top = top;
}, 0);
};
this.blur = function() {
text.blur();
};
this.isFocused = function() {
return isFocused;
};
var syncSelection = lang.delayedCall(function() {
isFocused && resetSelection(isSelectionEmpty);
});
var syncValue = lang.delayedCall(function() {
if (!inComposition) {
text.value = PLACEHOLDER;
isFocused && resetSelection();
}
});
function resetSelection(isEmpty) {
if (inComposition)
return;
inComposition = true;
if (inputHandler) {
selectionStart = 0;
selectionEnd = isEmpty ? 0 : text.value.length - 1;
} else {
var selectionStart = isEmpty ? 2 : 1;
var selectionEnd = 2;
}
try {
text.setSelectionRange(selectionStart, selectionEnd);
} catch(e){}
inComposition = false;
}
function resetValue() {
if (inComposition)
return;
text.value = PLACEHOLDER;
if (useragent.isWebKit)
syncValue.schedule();
}
useragent.isWebKit || host.addEventListener('changeSelection', function() {
if (host.selection.isEmpty() != isSelectionEmpty) {
isSelectionEmpty = !isSelectionEmpty;
syncSelection.schedule();
}
});
resetValue();
if (isFocused)
host.onFocus();
var isAllSelected = function(text) {
return text.selectionStart === 0 && text.selectionEnd === text.value.length;
};
if (!text.setSelectionRange && text.createTextRange) {
text.setSelectionRange = function(selectionStart, selectionEnd) {
var range = this.createTextRange();
range.collapse(true);
range.moveStart('character', selectionStart);
range.moveEnd('character', selectionEnd);
range.select();
};
isAllSelected = function(text) {
try {
var range = text.ownerDocument.selection.createRange();
}catch(e) {}
if (!range || range.parentElement() != text) return false;
return range.text == text.value;
}
}
if (useragent.isOldIE) {
var inPropertyChange = false;
var onPropertyChange = function(e){
if (inPropertyChange)
return;
var data = text.value;
if (inComposition || !data || data == PLACEHOLDER)
return;
if (e && data == PLACEHOLDER[0])
return syncProperty.schedule();
sendText(data);
inPropertyChange = true;
resetValue();
inPropertyChange = false;
};
var syncProperty = lang.delayedCall(onPropertyChange);
event.addListener(text, "propertychange", onPropertyChange);
var keytable = { 13:1, 27:1 };
event.addListener(text, "keyup", function (e) {
if (inComposition && (!text.value || keytable[e.keyCode]))
setTimeout(onCompositionEnd, 0);
if ((text.value.charCodeAt(0)||0) < 129) {
return syncProperty.call();
}
inComposition ? onCompositionUpdate() : onCompositionStart();
});
event.addListener(text, "keydown", function (e) {
syncProperty.schedule(50);
});
}
var onSelect = function(e) {
if (copied) {
copied = false;
} else if (isAllSelected(text)) {
host.selectAll();
resetSelection();
} else if (inputHandler) {
resetSelection(host.selection.isEmpty());
}
};
var inputHandler = null;
this.setInputHandler = function(cb) {inputHandler = cb};
this.getInputHandler = function() {return inputHandler};
var afterContextMenu = false;
var sendText = function(data) {
if (inputHandler) {
data = inputHandler(data);
inputHandler = null;
}
if (pasted) {
resetSelection();
if (data)
host.onPaste(data);
pasted = false;
} else if (data == PLACEHOLDER.charAt(0)) {
if (afterContextMenu)
host.execCommand("del", {source: "ace"});
else // some versions of android do not fire keydown when pressing backspace
host.execCommand("backspace", {source: "ace"});
} else {
if (data.substring(0, 2) == PLACEHOLDER)
data = data.substr(2);
else if (data.charAt(0) == PLACEHOLDER.charAt(0))
data = data.substr(1);
else if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data.charAt(data.length - 1) == PLACEHOLDER.charAt(0))
data = data.slice(0, -1);
if (data)
host.onTextInput(data);
}
if (afterContextMenu)
afterContextMenu = false;
};
var onInput = function(e) {
if (inComposition)
return;
var data = text.value;
sendText(data);
resetValue();
};
var handleClipboardData = function(e, data, forceIEMime) {
var clipboardData = e.clipboardData || window.clipboardData;
if (!clipboardData || BROKEN_SETDATA)
return;
var mime = USE_IE_MIME_TYPE || forceIEMime ? "Text" : "text/plain";
try {
if (data) {
return clipboardData.setData(mime, data) !== false;
} else {
return clipboardData.getData(mime);
}
} catch(e) {
if (!forceIEMime)
return handleClipboardData(e, data, true);
}
};
var doCopy = function(e, isCut) {
var data = host.getCopyText();
if (!data)
return event.preventDefault(e);
if (handleClipboardData(e, data)) {
isCut ? host.onCut() : host.onCopy();
event.preventDefault(e);
} else {
copied = true;
text.value = data;
text.select();
setTimeout(function(){
copied = false;
resetValue();
resetSelection();
isCut ? host.onCut() : host.onCopy();
});
}
};
var onCut = function(e) {
doCopy(e, true);
};
var onCopy = function(e) {
doCopy(e, false);
};
var onPaste = function(e) {
var data = handleClipboardData(e);
if (typeof data == "string") {
if (data)
host.onPaste(data, e);
if (useragent.isIE)
setTimeout(resetSelection);
event.preventDefault(e);
}
else {
text.value = "";
pasted = true;
}
};
event.addCommandKeyListener(text, host.onCommandKey.bind(host));
event.addListener(text, "select", onSelect);
event.addListener(text, "input", onInput);
event.addListener(text, "cut", onCut);
event.addListener(text, "copy", onCopy);
event.addListener(text, "paste", onPaste);
if (!('oncut' in text) || !('oncopy' in text) || !('onpaste' in text)){
event.addListener(parentNode, "keydown", function(e) {
if ((useragent.isMac && !e.metaKey) || !e.ctrlKey)
return;
switch (e.keyCode) {
case 67:
onCopy(e);
break;
case 86:
onPaste(e);
break;
case 88:
onCut(e);
break;
}
});
}
var onCompositionStart = function(e) {
if (inComposition || !host.onCompositionStart || host.$readOnly)
return;
inComposition = {};
inComposition.canUndo = host.session.$undoManager;
host.onCompositionStart();
setTimeout(onCompositionUpdate, 0);
host.on("mousedown", onCompositionEnd);
if (inComposition.canUndo && !host.selection.isEmpty()) {
host.insert("");
host.session.markUndoGroup();
host.selection.clearSelection();
}
host.session.markUndoGroup();
};
var onCompositionUpdate = function() {
if (!inComposition || !host.onCompositionUpdate || host.$readOnly)
return;
var val = text.value.replace(/\x01/g, "");
if (inComposition.lastValue === val) return;
host.onCompositionUpdate(val);
if (inComposition.lastValue)
host.undo();
if (inComposition.canUndo)
inComposition.lastValue = val;
if (inComposition.lastValue) {
var r = host.selection.getRange();
host.insert(inComposition.lastValue);
host.session.markUndoGroup();
inComposition.range = host.selection.getRange();
host.selection.setRange(r);
host.selection.clearSelection();
}
};
var onCompositionEnd = function(e) {
if (!host.onCompositionEnd || host.$readOnly) return;
var c = inComposition;
inComposition = false;
var timer = setTimeout(function() {
timer = null;
var str = text.value.replace(/\x01/g, "");
if (inComposition)
return;
else if (str == c.lastValue)
resetValue();
else if (!c.lastValue && str) {
resetValue();
sendText(str);
}
});
inputHandler = function compositionInputHandler(str) {
if (timer)
clearTimeout(timer);
str = str.replace(/\x01/g, "");
if (str == c.lastValue)
return "";
if (c.lastValue && timer)
host.undo();
return str;
};
host.onCompositionEnd();
host.removeListener("mousedown", onCompositionEnd);
if (e.type == "compositionend" && c.range) {
host.selection.setRange(c.range);
}
if (useragent.isChrome && useragent.isChrome >= 53) {
onInput();
}
};
var syncComposition = lang.delayedCall(onCompositionUpdate, 50);
event.addListener(text, "compositionstart", onCompositionStart);
if (useragent.isGecko) {
event.addListener(text, "text", function(){syncComposition.schedule()});
} else {
event.addListener(text, "keyup", function(){syncComposition.schedule()});
event.addListener(text, "keydown", function(){syncComposition.schedule()});
}
event.addListener(text, "compositionend", onCompositionEnd);
this.getElement = function() {
return text;
};
this.setReadOnly = function(readOnly) {
text.readOnly = readOnly;
};
this.onContextMenu = function(e) {
afterContextMenu = true;
resetSelection(host.selection.isEmpty());
host._emit("nativecontextmenu", {target: host, domEvent: e});
this.moveToMouse(e, true);
};
this.moveToMouse = function(e, bringToFront) {
if (!bringToFront && useragent.isOldIE)
return;
if (!tempStyle)
tempStyle = text.style.cssText;
text.style.cssText = (bringToFront ? "z-index:100000;" : "")
+ "height:" + text.style.height + ";"
+ (useragent.isIE ? "opacity:0.1;" : "");
var rect = host.container.getBoundingClientRect();
var style = dom.computedStyle(host.container);
var top = rect.top + (parseInt(style.borderTopWidth) || 0);
var left = rect.left + (parseInt(rect.borderLeftWidth) || 0);
var maxTop = rect.bottom - top - text.clientHeight -2;
var move = function(e) {
text.style.left = e.clientX - left - 2 + "px";
text.style.top = Math.min(e.clientY - top - 2, maxTop) + "px";
};
move(e);
if (e.type != "mousedown")
return;
if (host.renderer.$keepTextAreaAtCursor)
host.renderer.$keepTextAreaAtCursor = null;
clearTimeout(closeTimeout);
if (useragent.isWin && !useragent.isOldIE)
event.capture(host.container, move, onContextMenuClose);
};
this.onContextMenuClose = onContextMenuClose;
var closeTimeout;
function onContextMenuClose() {
clearTimeout(closeTimeout);
closeTimeout = setTimeout(function () {
if (tempStyle) {
text.style.cssText = tempStyle;
tempStyle = '';
}
if (host.renderer.$keepTextAreaAtCursor == null) {
host.renderer.$keepTextAreaAtCursor = true;
host.renderer.$moveTextAreaToCursor();
}
}, useragent.isOldIE ? 200 : 0);
}
var onContextMenu = function(e) {
host.textInput.onContextMenu(e);
onContextMenuClose();
};
event.addListener(text, "mouseup", onContextMenu);
event.addListener(text, "mousedown", function(e) {
e.preventDefault();
onContextMenuClose();
});
event.addListener(host.renderer.scroller, "contextmenu", onContextMenu);
event.addListener(text, "contextmenu", onContextMenu);
};
exports.TextInput = TextInput;
});
ace.define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
var DRAG_OFFSET = 0; // pixels
function DefaultHandlers(mouseHandler) {
mouseHandler.$clickSelection = null;
var editor = mouseHandler.editor;
editor.setDefaultHandler("mousedown", this.onMouseDown.bind(mouseHandler));
editor.setDefaultHandler("dblclick", this.onDoubleClick.bind(mouseHandler));
editor.setDefaultHandler("tripleclick", this.onTripleClick.bind(mouseHandler));
editor.setDefaultHandler("quadclick", this.onQuadClick.bind(mouseHandler));
editor.setDefaultHandler("mousewheel", this.onMouseWheel.bind(mouseHandler));
editor.setDefaultHandler("touchmove", this.onTouchMove.bind(mouseHandler));
var exports = ["select", "startSelect", "selectEnd", "selectAllEnd", "selectByWordsEnd",
"selectByLinesEnd", "dragWait", "dragWaitEnd", "focusWait"];
exports.forEach(function(x) {
mouseHandler[x] = this[x];
}, this);
mouseHandler.selectByLines = this.extendSelectionBy.bind(mouseHandler, "getLineRange");
mouseHandler.selectByWords = this.extendSelectionBy.bind(mouseHandler, "getWordRange");
}
(function() {
this.onMouseDown = function(ev) {
var inSelection = ev.inSelection();
var pos = ev.getDocumentPosition();
this.mousedownEvent = ev;
var editor = this.editor;
var button = ev.getButton();
if (button !== 0) {
var selectionRange = editor.getSelectionRange();
var selectionEmpty = selectionRange.isEmpty();
editor.$blockScrolling++;
if (selectionEmpty || button == 1)
editor.selection.moveToPosition(pos);
editor.$blockScrolling--;
if (button == 2)
editor.textInput.onContextMenu(ev.domEvent);
return; // stopping event here breaks contextmenu on ff mac
}
this.mousedownEvent.time = Date.now();
if (inSelection && !editor.isFocused()) {
editor.focus();
if (this.$focusTimout && !this.$clickSelection && !editor.inMultiSelectMode) {
this.setState("focusWait");
this.captureMouse(ev);
return;
}
}
this.captureMouse(ev);
this.startSelect(pos, ev.domEvent._clicks > 1);
return ev.preventDefault();
};
this.startSelect = function(pos, waitForClickSelection) {
pos = pos || this.editor.renderer.screenToTextCoordinates(this.x, this.y);
var editor = this.editor;
editor.$blockScrolling++;
if (this.mousedownEvent.getShiftKey())
editor.selection.selectToPosition(pos);
else if (!waitForClickSelection)
editor.selection.moveToPosition(pos);
if (!waitForClickSelection)
this.select();
if (editor.renderer.scroller.setCapture) {
editor.renderer.scroller.setCapture();
}
editor.setStyle("ace_selecting");
this.setState("select");
editor.$blockScrolling--;
};
this.select = function() {
var anchor, editor = this.editor;
var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
editor.$blockScrolling++;
if (this.$clickSelection) {
var cmp = this.$clickSelection.comparePoint(cursor);
if (cmp == -1) {
anchor = this.$clickSelection.end;
} else if (cmp == 1) {
anchor = this.$clickSelection.start;
} else {
var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
cursor = orientedRange.cursor;
anchor = orientedRange.anchor;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
}
editor.selection.selectToPosition(cursor);
editor.$blockScrolling--;
editor.renderer.scrollCursorIntoView();
};
this.extendSelectionBy = function(unitName) {
var anchor, editor = this.editor;
var cursor = editor.renderer.screenToTextCoordinates(this.x, this.y);
var range = editor.selection[unitName](cursor.row, cursor.column);
editor.$blockScrolling++;
if (this.$clickSelection) {
var cmpStart = this.$clickSelection.comparePoint(range.start);
var cmpEnd = this.$clickSelection.comparePoint(range.end);
if (cmpStart == -1 && cmpEnd <= 0) {
anchor = this.$clickSelection.end;
if (range.end.row != cursor.row || range.end.column != cursor.column)
cursor = range.start;
} else if (cmpEnd == 1 && cmpStart >= 0) {
anchor = this.$clickSelection.start;
if (range.start.row != cursor.row || range.start.column != cursor.column)
cursor = range.end;
} else if (cmpStart == -1 && cmpEnd == 1) {
cursor = range.end;
anchor = range.start;
} else {
var orientedRange = calcRangeOrientation(this.$clickSelection, cursor);
cursor = orientedRange.cursor;
anchor = orientedRange.anchor;
}
editor.selection.setSelectionAnchor(anchor.row, anchor.column);
}
editor.selection.selectToPosition(cursor);
editor.$blockScrolling--;
editor.renderer.scrollCursorIntoView();
};
this.selectEnd =
this.selectAllEnd =
this.selectByWordsEnd =
this.selectByLinesEnd = function() {
this.$clickSelection = null;
this.editor.unsetStyle("ace_selecting");
if (this.editor.renderer.scroller.releaseCapture) {
this.editor.renderer.scroller.releaseCapture();
}
};
this.focusWait = function() {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
var time = Date.now();
if (distance > DRAG_OFFSET || time - this.mousedownEvent.time > this.$focusTimout)
this.startSelect(this.mousedownEvent.getDocumentPosition());
};
this.onDoubleClick = function(ev) {
var pos = ev.getDocumentPosition();
var editor = this.editor;
var session = editor.session;
var range = session.getBracketRange(pos);
if (range) {
if (range.isEmpty()) {
range.start.column--;
range.end.column++;
}
this.setState("select");
} else {
range = editor.selection.getWordRange(pos.row, pos.column);
this.setState("selectByWords");
}
this.$clickSelection = range;
this.select();
};
this.onTripleClick = function(ev) {
var pos = ev.getDocumentPosition();
var editor = this.editor;
this.setState("selectByLines");
var range = editor.getSelectionRange();
if (range.isMultiLine() && range.contains(pos.row, pos.column)) {
this.$clickSelection = editor.selection.getLineRange(range.start.row);
this.$clickSelection.end = editor.selection.getLineRange(range.end.row).end;
} else {
this.$clickSelection = editor.selection.getLineRange(pos.row);
}
this.select();
};
this.onQuadClick = function(ev) {
var editor = this.editor;
editor.selectAll();
this.$clickSelection = editor.getSelectionRange();
this.setState("selectAll");
};
this.onMouseWheel = function(ev) {
if (ev.getAccelKey())
return;
if (ev.getShiftKey() && ev.wheelY && !ev.wheelX) {
ev.wheelX = ev.wheelY;
ev.wheelY = 0;
}
var t = ev.domEvent.timeStamp;
var dt = t - (this.$lastScrollTime||0);
var editor = this.editor;
var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
if (isScrolable || dt < 200) {
this.$lastScrollTime = t;
editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
return ev.stop();
}
};
this.onTouchMove = function (ev) {
var t = ev.domEvent.timeStamp;
var dt = t - (this.$lastScrollTime || 0);
var editor = this.editor;
var isScrolable = editor.renderer.isScrollableBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
if (isScrolable || dt < 200) {
this.$lastScrollTime = t;
editor.renderer.scrollBy(ev.wheelX * ev.speed, ev.wheelY * ev.speed);
return ev.stop();
}
};
}).call(DefaultHandlers.prototype);
exports.DefaultHandlers = DefaultHandlers;
function calcDistance(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
}
function calcRangeOrientation(range, cursor) {
if (range.start.row == range.end.row)
var cmp = 2 * cursor.column - range.start.column - range.end.column;
else if (range.start.row == range.end.row - 1 && !range.start.column && !range.end.column)
var cmp = cursor.column - 4;
else
var cmp = 2 * cursor.row - range.start.row - range.end.row;
if (cmp < 0)
return {cursor: range.start, anchor: range.end};
else
return {cursor: range.end, anchor: range.start};
}
});
ace.define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var dom = acequire("./lib/dom");
function Tooltip (parentNode) {
this.isOpen = false;
this.$element = null;
this.$parentNode = parentNode;
}
(function() {
this.$init = function() {
this.$element = dom.createElement("div");
this.$element.className = "ace_tooltip";
this.$element.style.display = "none";
this.$parentNode.appendChild(this.$element);
return this.$element;
};
this.getElement = function() {
return this.$element || this.$init();
};
this.setText = function(text) {
dom.setInnerText(this.getElement(), text);
};
this.setHtml = function(html) {
this.getElement().innerHTML = html;
};
this.setPosition = function(x, y) {
this.getElement().style.left = x + "px";
this.getElement().style.top = y + "px";
};
this.setClassName = function(className) {
dom.addCssClass(this.getElement(), className);
};
this.show = function(text, x, y) {
if (text != null)
this.setText(text);
if (x != null && y != null)
this.setPosition(x, y);
if (!this.isOpen) {
this.getElement().style.display = "block";
this.isOpen = true;
}
};
this.hide = function() {
if (this.isOpen) {
this.getElement().style.display = "none";
this.isOpen = false;
}
};
this.getHeight = function() {
return this.getElement().offsetHeight;
};
this.getWidth = function() {
return this.getElement().offsetWidth;
};
}).call(Tooltip.prototype);
exports.Tooltip = Tooltip;
});
ace.define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var oop = acequire("../lib/oop");
var event = acequire("../lib/event");
var Tooltip = acequire("../tooltip").Tooltip;
function GutterHandler(mouseHandler) {
var editor = mouseHandler.editor;
var gutter = editor.renderer.$gutterLayer;
var tooltip = new GutterTooltip(editor.container);
mouseHandler.editor.setDefaultHandler("guttermousedown", function(e) {
if (!editor.isFocused() || e.getButton() != 0)
return;
var gutterRegion = gutter.getRegion(e);
if (gutterRegion == "foldWidgets")
return;
var row = e.getDocumentPosition().row;
var selection = editor.session.selection;
if (e.getShiftKey())
selection.selectTo(row, 0);
else {
if (e.domEvent.detail == 2) {
editor.selectAll();
return e.preventDefault();
}
mouseHandler.$clickSelection = editor.selection.getLineRange(row);
}
mouseHandler.setState("selectByLines");
mouseHandler.captureMouse(e);
return e.preventDefault();
});
var tooltipTimeout, mouseEvent, tooltipAnnotation;
function showTooltip() {
var row = mouseEvent.getDocumentPosition().row;
var annotation = gutter.$annotations[row];
if (!annotation)
return hideTooltip();
var maxRow = editor.session.getLength();
if (row == maxRow) {
var screenRow = editor.renderer.pixelToScreenCoordinates(0, mouseEvent.y).row;
var pos = mouseEvent.$pos;
if (screenRow > editor.session.documentToScreenRow(pos.row, pos.column))
return hideTooltip();
}
if (tooltipAnnotation == annotation)
return;
tooltipAnnotation = annotation.text.join("<br/>");
tooltip.setHtml(tooltipAnnotation);
tooltip.show();
editor._signal("showGutterTooltip", tooltip);
editor.on("mousewheel", hideTooltip);
if (mouseHandler.$tooltipFollowsMouse) {
moveTooltip(mouseEvent);
} else {
var gutterElement = mouseEvent.domEvent.target;
var rect = gutterElement.getBoundingClientRect();
var style = tooltip.getElement().style;
style.left = rect.right + "px";
style.top = rect.bottom + "px";
}
}
function hideTooltip() {
if (tooltipTimeout)
tooltipTimeout = clearTimeout(tooltipTimeout);
if (tooltipAnnotation) {
tooltip.hide();
tooltipAnnotation = null;
editor._signal("hideGutterTooltip", tooltip);
editor.removeEventListener("mousewheel", hideTooltip);
}
}
function moveTooltip(e) {
tooltip.setPosition(e.x, e.y);
}
mouseHandler.editor.setDefaultHandler("guttermousemove", function(e) {
var target = e.domEvent.target || e.domEvent.srcElement;
if (dom.hasCssClass(target, "ace_fold-widget"))
return hideTooltip();
if (tooltipAnnotation && mouseHandler.$tooltipFollowsMouse)
moveTooltip(e);
mouseEvent = e;
if (tooltipTimeout)
return;
tooltipTimeout = setTimeout(function() {
tooltipTimeout = null;
if (mouseEvent && !mouseHandler.isMousePressed)
showTooltip();
else
hideTooltip();
}, 50);
});
event.addListener(editor.renderer.$gutter, "mouseout", function(e) {
mouseEvent = null;
if (!tooltipAnnotation || tooltipTimeout)
return;
tooltipTimeout = setTimeout(function() {
tooltipTimeout = null;
hideTooltip();
}, 50);
});
editor.on("changeSession", hideTooltip);
}
function GutterTooltip(parentNode) {
Tooltip.call(this, parentNode);
}
oop.inherits(GutterTooltip, Tooltip);
(function(){
this.setPosition = function(x, y) {
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var width = this.getWidth();
var height = this.getHeight();
x += 15;
y += 15;
if (x + width > windowWidth) {
x -= (x + width) - windowWidth;
}
if (y + height > windowHeight) {
y -= 20 + height;
}
Tooltip.prototype.setPosition.call(this, x, y);
};
}).call(GutterTooltip.prototype);
exports.GutterHandler = GutterHandler;
});
ace.define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) {
"use strict";
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
var MouseEvent = exports.MouseEvent = function(domEvent, editor) {
this.domEvent = domEvent;
this.editor = editor;
this.x = this.clientX = domEvent.clientX;
this.y = this.clientY = domEvent.clientY;
this.$pos = null;
this.$inSelection = null;
this.propagationStopped = false;
this.defaultPrevented = false;
};
(function() {
this.stopPropagation = function() {
event.stopPropagation(this.domEvent);
this.propagationStopped = true;
};
this.preventDefault = function() {
event.preventDefault(this.domEvent);
this.defaultPrevented = true;
};
this.stop = function() {
this.stopPropagation();
this.preventDefault();
};
this.getDocumentPosition = function() {
if (this.$pos)
return this.$pos;
this.$pos = this.editor.renderer.screenToTextCoordinates(this.clientX, this.clientY);
return this.$pos;
};
this.inSelection = function() {
if (this.$inSelection !== null)
return this.$inSelection;
var editor = this.editor;
var selectionRange = editor.getSelectionRange();
if (selectionRange.isEmpty())
this.$inSelection = false;
else {
var pos = this.getDocumentPosition();
this.$inSelection = selectionRange.contains(pos.row, pos.column);
}
return this.$inSelection;
};
this.getButton = function() {
return event.getButton(this.domEvent);
};
this.getShiftKey = function() {
return this.domEvent.shiftKey;
};
this.getAccelKey = useragent.isMac
? function() { return this.domEvent.metaKey; }
: function() { return this.domEvent.ctrlKey; };
}).call(MouseEvent.prototype);
});
ace.define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
var AUTOSCROLL_DELAY = 200;
var SCROLL_CURSOR_DELAY = 200;
var SCROLL_CURSOR_HYSTERESIS = 5;
function DragdropHandler(mouseHandler) {
var editor = mouseHandler.editor;
var blankImage = dom.createElement("img");
blankImage.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
if (useragent.isOpera)
blankImage.style.cssText = "width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;";
var exports = ["dragWait", "dragWaitEnd", "startDrag", "dragReadyEnd", "onMouseDrag"];
exports.forEach(function(x) {
mouseHandler[x] = this[x];
}, this);
editor.addEventListener("mousedown", this.onMouseDown.bind(mouseHandler));
var mouseTarget = editor.container;
var dragSelectionMarker, x, y;
var timerId, range;
var dragCursor, counter = 0;
var dragOperation;
var isInternal;
var autoScrollStartTime;
var cursorMovedTime;
var cursorPointOnCaretMoved;
this.onDragStart = function(e) {
if (this.cancelDrag || !mouseTarget.draggable) {
var self = this;
setTimeout(function(){
self.startSelect();
self.captureMouse(e);
}, 0);
return e.preventDefault();
}
range = editor.getSelectionRange();
var dataTransfer = e.dataTransfer;
dataTransfer.effectAllowed = editor.getReadOnly() ? "copy" : "copyMove";
if (useragent.isOpera) {
editor.container.appendChild(blankImage);
blankImage.scrollTop = 0;
}
dataTransfer.setDragImage && dataTransfer.setDragImage(blankImage, 0, 0);
if (useragent.isOpera) {
editor.container.removeChild(blankImage);
}
dataTransfer.clearData();
dataTransfer.setData("Text", editor.session.getTextRange());
isInternal = true;
this.setState("drag");
};
this.onDragEnd = function(e) {
mouseTarget.draggable = false;
isInternal = false;
this.setState(null);
if (!editor.getReadOnly()) {
var dropEffect = e.dataTransfer.dropEffect;
if (!dragOperation && dropEffect == "move")
editor.session.remove(editor.getSelectionRange());
editor.renderer.$cursorLayer.setBlinking(true);
}
this.editor.unsetStyle("ace_dragging");
this.editor.renderer.setCursorStyle("");
};
this.onDragEnter = function(e) {
if (editor.getReadOnly() || !canAccept(e.dataTransfer))
return;
x = e.clientX;
y = e.clientY;
if (!dragSelectionMarker)
addDragMarker();
counter++;
e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
return event.preventDefault(e);
};
this.onDragOver = function(e) {
if (editor.getReadOnly() || !canAccept(e.dataTransfer))
return;
x = e.clientX;
y = e.clientY;
if (!dragSelectionMarker) {
addDragMarker();
counter++;
}
if (onMouseMoveTimer !== null)
onMouseMoveTimer = null;
e.dataTransfer.dropEffect = dragOperation = getDropEffect(e);
return event.preventDefault(e);
};
this.onDragLeave = function(e) {
counter--;
if (counter <= 0 && dragSelectionMarker) {
clearDragMarker();
dragOperation = null;
return event.preventDefault(e);
}
};
this.onDrop = function(e) {
if (!dragCursor)
return;
var dataTransfer = e.dataTransfer;
if (isInternal) {
switch (dragOperation) {
case "move":
if (range.contains(dragCursor.row, dragCursor.column)) {
range = {
start: dragCursor,
end: dragCursor
};
} else {
range = editor.moveText(range, dragCursor);
}
break;
case "copy":
range = editor.moveText(range, dragCursor, true);
break;
}
} else {
var dropData = dataTransfer.getData('Text');
range = {
start: dragCursor,
end: editor.session.insert(dragCursor, dropData)
};
editor.focus();
dragOperation = null;
}
clearDragMarker();
return event.preventDefault(e);
};
event.addListener(mouseTarget, "dragstart", this.onDragStart.bind(mouseHandler));
event.addListener(mouseTarget, "dragend", this.onDragEnd.bind(mouseHandler));
event.addListener(mouseTarget, "dragenter", this.onDragEnter.bind(mouseHandler));
event.addListener(mouseTarget, "dragover", this.onDragOver.bind(mouseHandler));
event.addListener(mouseTarget, "dragleave", this.onDragLeave.bind(mouseHandler));
event.addListener(mouseTarget, "drop", this.onDrop.bind(mouseHandler));
function scrollCursorIntoView(cursor, prevCursor) {
var now = Date.now();
var vMovement = !prevCursor || cursor.row != prevCursor.row;
var hMovement = !prevCursor || cursor.column != prevCursor.column;
if (!cursorMovedTime || vMovement || hMovement) {
editor.$blockScrolling += 1;
editor.moveCursorToPosition(cursor);
editor.$blockScrolling -= 1;
cursorMovedTime = now;
cursorPointOnCaretMoved = {x: x, y: y};
} else {
var distance = calcDistance(cursorPointOnCaretMoved.x, cursorPointOnCaretMoved.y, x, y);
if (distance > SCROLL_CURSOR_HYSTERESIS) {
cursorMovedTime = null;
} else if (now - cursorMovedTime >= SCROLL_CURSOR_DELAY) {
editor.renderer.scrollCursorIntoView();
cursorMovedTime = null;
}
}
}
function autoScroll(cursor, prevCursor) {
var now = Date.now();
var lineHeight = editor.renderer.layerConfig.lineHeight;
var characterWidth = editor.renderer.layerConfig.characterWidth;
var editorRect = editor.renderer.scroller.getBoundingClientRect();
var offsets = {
x: {
left: x - editorRect.left,
right: editorRect.right - x
},
y: {
top: y - editorRect.top,
bottom: editorRect.bottom - y
}
};
var nearestXOffset = Math.min(offsets.x.left, offsets.x.right);
var nearestYOffset = Math.min(offsets.y.top, offsets.y.bottom);
var scrollCursor = {row: cursor.row, column: cursor.column};
if (nearestXOffset / characterWidth <= 2) {
scrollCursor.column += (offsets.x.left < offsets.x.right ? -3 : +2);
}
if (nearestYOffset / lineHeight <= 1) {
scrollCursor.row += (offsets.y.top < offsets.y.bottom ? -1 : +1);
}
var vScroll = cursor.row != scrollCursor.row;
var hScroll = cursor.column != scrollCursor.column;
var vMovement = !prevCursor || cursor.row != prevCursor.row;
if (vScroll || (hScroll && !vMovement)) {
if (!autoScrollStartTime)
autoScrollStartTime = now;
else if (now - autoScrollStartTime >= AUTOSCROLL_DELAY)
editor.renderer.scrollCursorIntoView(scrollCursor);
} else {
autoScrollStartTime = null;
}
}
function onDragInterval() {
var prevCursor = dragCursor;
dragCursor = editor.renderer.screenToTextCoordinates(x, y);
scrollCursorIntoView(dragCursor, prevCursor);
autoScroll(dragCursor, prevCursor);
}
function addDragMarker() {
range = editor.selection.toOrientedRange();
dragSelectionMarker = editor.session.addMarker(range, "ace_selection", editor.getSelectionStyle());
editor.clearSelection();
if (editor.isFocused())
editor.renderer.$cursorLayer.setBlinking(false);
clearInterval(timerId);
onDragInterval();
timerId = setInterval(onDragInterval, 20);
counter = 0;
event.addListener(document, "mousemove", onMouseMove);
}
function clearDragMarker() {
clearInterval(timerId);
editor.session.removeMarker(dragSelectionMarker);
dragSelectionMarker = null;
editor.$blockScrolling += 1;
editor.selection.fromOrientedRange(range);
editor.$blockScrolling -= 1;
if (editor.isFocused() && !isInternal)
editor.renderer.$cursorLayer.setBlinking(!editor.getReadOnly());
range = null;
dragCursor = null;
counter = 0;
autoScrollStartTime = null;
cursorMovedTime = null;
event.removeListener(document, "mousemove", onMouseMove);
}
var onMouseMoveTimer = null;
function onMouseMove() {
if (onMouseMoveTimer == null) {
onMouseMoveTimer = setTimeout(function() {
if (onMouseMoveTimer != null && dragSelectionMarker)
clearDragMarker();
}, 20);
}
}
function canAccept(dataTransfer) {
var types = dataTransfer.types;
return !types || Array.prototype.some.call(types, function(type) {
return type == 'text/plain' || type == 'Text';
});
}
function getDropEffect(e) {
var copyAllowed = ['copy', 'copymove', 'all', 'uninitialized'];
var moveAllowed = ['move', 'copymove', 'linkmove', 'all', 'uninitialized'];
var copyModifierState = useragent.isMac ? e.altKey : e.ctrlKey;
var effectAllowed = "uninitialized";
try {
effectAllowed = e.dataTransfer.effectAllowed.toLowerCase();
} catch (e) {}
var dropEffect = "none";
if (copyModifierState && copyAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "copy";
else if (moveAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "move";
else if (copyAllowed.indexOf(effectAllowed) >= 0)
dropEffect = "copy";
return dropEffect;
}
}
(function() {
this.dragWait = function() {
var interval = Date.now() - this.mousedownEvent.time;
if (interval > this.editor.getDragDelay())
this.startDrag();
};
this.dragWaitEnd = function() {
var target = this.editor.container;
target.draggable = false;
this.startSelect(this.mousedownEvent.getDocumentPosition());
this.selectEnd();
};
this.dragReadyEnd = function(e) {
this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly());
this.editor.unsetStyle("ace_dragging");
this.editor.renderer.setCursorStyle("");
this.dragWaitEnd();
};
this.startDrag = function(){
this.cancelDrag = false;
var editor = this.editor;
var target = editor.container;
target.draggable = true;
editor.renderer.$cursorLayer.setBlinking(false);
editor.setStyle("ace_dragging");
var cursorStyle = useragent.isWin ? "default" : "move";
editor.renderer.setCursorStyle(cursorStyle);
this.setState("dragReady");
};
this.onMouseDrag = function(e) {
var target = this.editor.container;
if (useragent.isIE && this.state == "dragReady") {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
if (distance > 3)
target.dragDrop();
}
if (this.state === "dragWait") {
var distance = calcDistance(this.mousedownEvent.x, this.mousedownEvent.y, this.x, this.y);
if (distance > 0) {
target.draggable = false;
this.startSelect(this.mousedownEvent.getDocumentPosition());
}
}
};
this.onMouseDown = function(e) {
if (!this.$dragEnabled)
return;
this.mousedownEvent = e;
var editor = this.editor;
var inSelection = e.inSelection();
var button = e.getButton();
var clickCount = e.domEvent.detail || 1;
if (clickCount === 1 && button === 0 && inSelection) {
if (e.editor.inMultiSelectMode && (e.getAccelKey() || e.getShiftKey()))
return;
this.mousedownEvent.time = Date.now();
var eventTarget = e.domEvent.target || e.domEvent.srcElement;
if ("unselectable" in eventTarget)
eventTarget.unselectable = "on";
if (editor.getDragDelay()) {
if (useragent.isWebKit) {
this.cancelDrag = true;
var mouseTarget = editor.container;
mouseTarget.draggable = true;
}
this.setState("dragWait");
} else {
this.startDrag();
}
this.captureMouse(e, this.onMouseDrag.bind(this));
e.defaultPrevented = true;
}
};
}).call(DragdropHandler.prototype);
function calcDistance(ax, ay, bx, by) {
return Math.sqrt(Math.pow(bx - ax, 2) + Math.pow(by - ay, 2));
}
exports.DragdropHandler = DragdropHandler;
});
ace.define("ace/lib/net",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
"use strict";
var dom = acequire("./dom");
exports.get = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
};
exports.loadScript = function(path, callback) {
var head = dom.getDocumentHead();
var s = document.createElement('script');
s.src = path;
head.appendChild(s);
s.onload = s.onreadystatechange = function(_, isAbort) {
if (isAbort || !s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
s = s.onload = s.onreadystatechange = null;
if (!isAbort)
callback();
}
};
};
exports.qualifyURL = function(url) {
var a = document.createElement('a');
a.href = url;
return a.href;
}
});
ace.define("ace/lib/event_emitter",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var EventEmitter = {};
var stopPropagation = function() { this.propagationStopped = true; };
var preventDefault = function() { this.defaultPrevented = true; };
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry || (this._eventRegistry = {});
this._defaultHandlers || (this._defaultHandlers = {});
var listeners = this._eventRegistry[eventName] || [];
var defaultHandler = this._defaultHandlers[eventName];
if (!listeners.length && !defaultHandler)
return;
if (typeof e != "object" || !e)
e = {};
if (!e.type)
e.type = eventName;
if (!e.stopPropagation)
e.stopPropagation = stopPropagation;
if (!e.preventDefault)
e.preventDefault = preventDefault;
listeners = listeners.slice();
for (var i=0; i<listeners.length; i++) {
listeners[i](e, this);
if (e.propagationStopped)
break;
}
if (defaultHandler && !e.defaultPrevented)
return defaultHandler(e, this);
};
EventEmitter._signal = function(eventName, e) {
var listeners = (this._eventRegistry || {})[eventName];
if (!listeners)
return;
listeners = listeners.slice();
for (var i=0; i<listeners.length; i++)
listeners[i](e, this);
};
EventEmitter.once = function(eventName, callback) {
var _self = this;
callback && this.addEventListener(eventName, function newCallback() {
_self.removeEventListener(eventName, newCallback);
callback.apply(null, arguments);
});
};
EventEmitter.setDefaultHandler = function(eventName, callback) {
var handlers = this._defaultHandlers
if (!handlers)
handlers = this._defaultHandlers = {_disabled_: {}};
if (handlers[eventName]) {
var old = handlers[eventName];
var disabled = handlers._disabled_[eventName];
if (!disabled)
handlers._disabled_[eventName] = disabled = [];
disabled.push(old);
var i = disabled.indexOf(callback);
if (i != -1)
disabled.splice(i, 1);
}
handlers[eventName] = callback;
};
EventEmitter.removeDefaultHandler = function(eventName, callback) {
var handlers = this._defaultHandlers
if (!handlers)
return;
var disabled = handlers._disabled_[eventName];
if (handlers[eventName] == callback) {
var old = handlers[eventName];
if (disabled)
this.setDefaultHandler(eventName, disabled.pop());
} else if (disabled) {
var i = disabled.indexOf(callback);
if (i != -1)
disabled.splice(i, 1);
}
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback, capturing) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
listeners = this._eventRegistry[eventName] = [];
if (listeners.indexOf(callback) == -1)
listeners[capturing ? "unshift" : "push"](callback);
return callback;
};
EventEmitter.off =
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
return;
var index = listeners.indexOf(callback);
if (index !== -1)
listeners.splice(index, 1);
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
};
exports.EventEmitter = EventEmitter;
});
ace.define("ace/lib/app_config",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) {
"no use strict";
var oop = acequire("./oop");
var EventEmitter = acequire("./event_emitter").EventEmitter;
var optionsProvider = {
setOptions: function(optList) {
Object.keys(optList).forEach(function(key) {
this.setOption(key, optList[key]);
}, this);
},
getOptions: function(optionNames) {
var result = {};
if (!optionNames) {
optionNames = Object.keys(this.$options);
} else if (!Array.isArray(optionNames)) {
result = optionNames;
optionNames = Object.keys(result);
}
optionNames.forEach(function(key) {
result[key] = this.getOption(key);
}, this);
return result;
},
setOption: function(name, value) {
if (this["$" + name] === value)
return;
var opt = this.$options[name];
if (!opt) {
return warn('misspelled option "' + name + '"');
}
if (opt.forwardTo)
return this[opt.forwardTo] && this[opt.forwardTo].setOption(name, value);
if (!opt.handlesSet)
this["$" + name] = value;
if (opt && opt.set)
opt.set.call(this, value);
},
getOption: function(name) {
var opt = this.$options[name];
if (!opt) {
return warn('misspelled option "' + name + '"');
}
if (opt.forwardTo)
return this[opt.forwardTo] && this[opt.forwardTo].getOption(name);
return opt && opt.get ? opt.get.call(this) : this["$" + name];
}
};
function warn(message) {
if (typeof console != "undefined" && console.warn)
console.warn.apply(console, arguments);
}
function reportError(msg, data) {
var e = new Error(msg);
e.data = data;
if (typeof console == "object" && console.error)
console.error(e);
setTimeout(function() { throw e; });
}
var AppConfig = function() {
this.$defaultOptions = {};
};
(function() {
oop.implement(this, EventEmitter);
this.defineOptions = function(obj, path, options) {
if (!obj.$options)
this.$defaultOptions[path] = obj.$options = {};
Object.keys(options).forEach(function(key) {
var opt = options[key];
if (typeof opt == "string")
opt = {forwardTo: opt};
opt.name || (opt.name = key);
obj.$options[opt.name] = opt;
if ("initialValue" in opt)
obj["$" + opt.name] = opt.initialValue;
});
oop.implement(obj, optionsProvider);
return this;
};
this.resetOptions = function(obj) {
Object.keys(obj.$options).forEach(function(key) {
var opt = obj.$options[key];
if ("value" in opt)
obj.setOption(key, opt.value);
});
};
this.setDefaultValue = function(path, name, value) {
var opts = this.$defaultOptions[path] || (this.$defaultOptions[path] = {});
if (opts[name]) {
if (opts.forwardTo)
this.setDefaultValue(opts.forwardTo, name, value);
else
opts[name].value = value;
}
};
this.setDefaultValues = function(path, optionHash) {
Object.keys(optionHash).forEach(function(key) {
this.setDefaultValue(path, key, optionHash[key]);
}, this);
};
this.warn = warn;
this.reportError = reportError;
}).call(AppConfig.prototype);
exports.AppConfig = AppConfig;
});
ace.define("ace/config",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/lib/net","ace/lib/app_config"], function(acequire, exports, module) {
"no use strict";
var lang = acequire("./lib/lang");
var oop = acequire("./lib/oop");
var net = acequire("./lib/net");
var AppConfig = acequire("./lib/app_config").AppConfig;
module.exports = exports = new AppConfig();
var global = (function() {
return this || typeof window != "undefined" && window;
})();
var options = {
packaged: false,
workerPath: null,
modePath: null,
themePath: null,
basePath: "",
suffix: ".js",
$moduleUrls: {}
};
exports.get = function(key) {
if (!options.hasOwnProperty(key))
throw new Error("Unknown config key: " + key);
return options[key];
};
exports.set = function(key, value) {
if (!options.hasOwnProperty(key))
throw new Error("Unknown config key: " + key);
options[key] = value;
};
exports.all = function() {
return lang.copyObject(options);
};
exports.moduleUrl = function(name, component) {
if (options.$moduleUrls[name])
return options.$moduleUrls[name];
var parts = name.split("/");
component = component || parts[parts.length - 2] || "";
var sep = component == "snippets" ? "/" : "-";
var base = parts[parts.length - 1];
if (component == "worker" && sep == "-") {
var re = new RegExp("^" + component + "[\\-_]|[\\-_]" + component + "$", "g");
base = base.replace(re, "");
}
if ((!base || base == component) && parts.length > 1)
base = parts[parts.length - 2];
var path = options[component + "Path"];
if (path == null) {
path = options.basePath;
} else if (sep == "/") {
component = sep = "";
}
if (path && path.slice(-1) != "/")
path += "/";
return path + component + sep + base + this.get("suffix");
};
exports.setModuleUrl = function(name, subst) {
return options.$moduleUrls[name] = subst;
};
exports.$loading = {};
exports.loadModule = function(moduleName, onLoad) {
var module, moduleType;
if (Array.isArray(moduleName)) {
moduleType = moduleName[0];
moduleName = moduleName[1];
}
try {
module = acequire(moduleName);
} catch (e) {}
if (module && !exports.$loading[moduleName])
return onLoad && onLoad(module);
if (!exports.$loading[moduleName])
exports.$loading[moduleName] = [];
exports.$loading[moduleName].push(onLoad);
if (exports.$loading[moduleName].length > 1)
return;
var afterLoad = function() {
acequire([moduleName], function(module) {
exports._emit("load.module", {name: moduleName, module: module});
var listeners = exports.$loading[moduleName];
exports.$loading[moduleName] = null;
listeners.forEach(function(onLoad) {
onLoad && onLoad(module);
});
});
};
if (!exports.get("packaged"))
return afterLoad();
net.loadScript(exports.moduleUrl(moduleName, moduleType), afterLoad);
};
init(true);function init(packaged) {
if (!global || !global.document)
return;
options.packaged = packaged || acequire.packaged || module.packaged || (global.define && __webpack_require__(34).packaged);
var scriptOptions = {};
var scriptUrl = "";
var currentScript = (document.currentScript || document._currentScript ); // native or polyfill
var currentDocument = currentScript && currentScript.ownerDocument || document;
var scripts = currentDocument.getElementsByTagName("script");
for (var i=0; i<scripts.length; i++) {
var script = scripts[i];
var src = script.src || script.getAttribute("src");
if (!src)
continue;
var attributes = script.attributes;
for (var j=0, l=attributes.length; j < l; j++) {
var attr = attributes[j];
if (attr.name.indexOf("data-ace-") === 0) {
scriptOptions[deHyphenate(attr.name.replace(/^data-ace-/, ""))] = attr.value;
}
}
var m = src.match(/^(.*)\/ace(\-\w+)?\.js(\?|$)/);
if (m)
scriptUrl = m[1];
}
if (scriptUrl) {
scriptOptions.base = scriptOptions.base || scriptUrl;
scriptOptions.packaged = true;
}
scriptOptions.basePath = scriptOptions.base;
scriptOptions.workerPath = scriptOptions.workerPath || scriptOptions.base;
scriptOptions.modePath = scriptOptions.modePath || scriptOptions.base;
scriptOptions.themePath = scriptOptions.themePath || scriptOptions.base;
delete scriptOptions.base;
for (var key in scriptOptions)
if (typeof scriptOptions[key] !== "undefined")
exports.set(key, scriptOptions[key]);
}
exports.init = init;
function deHyphenate(str) {
return str.replace(/-(.)/g, function(m, m1) { return m1.toUpperCase(); });
}
});
ace.define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event","ace/mouse/dragdrop_handler","ace/config"], function(acequire, exports, module) {
"use strict";
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
var DefaultHandlers = acequire("./default_handlers").DefaultHandlers;
var DefaultGutterHandler = acequire("./default_gutter_handler").GutterHandler;
var MouseEvent = acequire("./mouse_event").MouseEvent;
var DragdropHandler = acequire("./dragdrop_handler").DragdropHandler;
var config = acequire("../config");
var MouseHandler = function(editor) {
var _self = this;
this.editor = editor;
new DefaultHandlers(this);
new DefaultGutterHandler(this);
new DragdropHandler(this);
var focusEditor = function(e) {
var windowBlurred = !document.hasFocus || !document.hasFocus()
|| !editor.isFocused() && document.activeElement == (editor.textInput && editor.textInput.getElement())
if (windowBlurred)
window.focus();
editor.focus();
};
var mouseTarget = editor.renderer.getMouseEventTarget();
event.addListener(mouseTarget, "click", this.onMouseEvent.bind(this, "click"));
event.addListener(mouseTarget, "mousemove", this.onMouseMove.bind(this, "mousemove"));
event.addMultiMouseDownListener([
mouseTarget,
editor.renderer.scrollBarV && editor.renderer.scrollBarV.inner,
editor.renderer.scrollBarH && editor.renderer.scrollBarH.inner,
editor.textInput && editor.textInput.getElement()
].filter(Boolean), [400, 300, 250], this, "onMouseEvent");
event.addMouseWheelListener(editor.container, this.onMouseWheel.bind(this, "mousewheel"));
event.addTouchMoveListener(editor.container, this.onTouchMove.bind(this, "touchmove"));
var gutterEl = editor.renderer.$gutter;
event.addListener(gutterEl, "mousedown", this.onMouseEvent.bind(this, "guttermousedown"));
event.addListener(gutterEl, "click", this.onMouseEvent.bind(this, "gutterclick"));
event.addListener(gutterEl, "dblclick", this.onMouseEvent.bind(this, "gutterdblclick"));
event.addListener(gutterEl, "mousemove", this.onMouseEvent.bind(this, "guttermousemove"));
event.addListener(mouseTarget, "mousedown", focusEditor);
event.addListener(gutterEl, "mousedown", focusEditor);
if (useragent.isIE && editor.renderer.scrollBarV) {
event.addListener(editor.renderer.scrollBarV.element, "mousedown", focusEditor);
event.addListener(editor.renderer.scrollBarH.element, "mousedown", focusEditor);
}
editor.on("mousemove", function(e){
if (_self.state || _self.$dragDelay || !_self.$dragEnabled)
return;
var character = editor.renderer.screenToTextCoordinates(e.x, e.y);
var range = editor.session.selection.getRange();
var renderer = editor.renderer;
if (!range.isEmpty() && range.insideStart(character.row, character.column)) {
renderer.setCursorStyle("default");
} else {
renderer.setCursorStyle("");
}
});
};
(function() {
this.onMouseEvent = function(name, e) {
this.editor._emit(name, new MouseEvent(e, this.editor));
};
this.onMouseMove = function(name, e) {
var listeners = this.editor._eventRegistry && this.editor._eventRegistry.mousemove;
if (!listeners || !listeners.length)
return;
this.editor._emit(name, new MouseEvent(e, this.editor));
};
this.onMouseWheel = function(name, e) {
var mouseEvent = new MouseEvent(e, this.editor);
mouseEvent.speed = this.$scrollSpeed * 2;
mouseEvent.wheelX = e.wheelX;
mouseEvent.wheelY = e.wheelY;
this.editor._emit(name, mouseEvent);
};
this.onTouchMove = function (name, e) {
var mouseEvent = new MouseEvent(e, this.editor);
mouseEvent.speed = 1;//this.$scrollSpeed * 2;
mouseEvent.wheelX = e.wheelX;
mouseEvent.wheelY = e.wheelY;
this.editor._emit(name, mouseEvent);
};
this.setState = function(state) {
this.state = state;
};
this.captureMouse = function(ev, mouseMoveHandler) {
this.x = ev.x;
this.y = ev.y;
this.isMousePressed = true;
var renderer = this.editor.renderer;
if (renderer.$keepTextAreaAtCursor)
renderer.$keepTextAreaAtCursor = null;
var self = this;
var onMouseMove = function(e) {
if (!e) return;
if (useragent.isWebKit && !e.which && self.releaseMouse)
return self.releaseMouse();
self.x = e.clientX;
self.y = e.clientY;
mouseMoveHandler && mouseMoveHandler(e);
self.mouseEvent = new MouseEvent(e, self.editor);
self.$mouseMoved = true;
};
var onCaptureEnd = function(e) {
clearInterval(timerId);
onCaptureInterval();
self[self.state + "End"] && self[self.state + "End"](e);
self.state = "";
if (renderer.$keepTextAreaAtCursor == null) {
renderer.$keepTextAreaAtCursor = true;
renderer.$moveTextAreaToCursor();
}
self.isMousePressed = false;
self.$onCaptureMouseMove = self.releaseMouse = null;
e && self.onMouseEvent("mouseup", e);
};
var onCaptureInterval = function() {
self[self.state] && self[self.state]();
self.$mouseMoved = false;
};
if (useragent.isOldIE && ev.domEvent.type == "dblclick") {
return setTimeout(function() {onCaptureEnd(ev);});
}
self.$onCaptureMouseMove = onMouseMove;
self.releaseMouse = event.capture(this.editor.container, onMouseMove, onCaptureEnd);
var timerId = setInterval(onCaptureInterval, 20);
};
this.releaseMouse = null;
this.cancelContextMenu = function() {
var stop = function(e) {
if (e && e.domEvent && e.domEvent.type != "contextmenu")
return;
this.editor.off("nativecontextmenu", stop);
if (e && e.domEvent)
event.stopEvent(e.domEvent);
}.bind(this);
setTimeout(stop, 10);
this.editor.on("nativecontextmenu", stop);
};
}).call(MouseHandler.prototype);
config.defineOptions(MouseHandler.prototype, "mouseHandler", {
scrollSpeed: {initialValue: 2},
dragDelay: {initialValue: (useragent.isMac ? 150 : 0)},
dragEnabled: {initialValue: true},
focusTimout: {initialValue: 0},
tooltipFollowsMouse: {initialValue: true}
});
exports.MouseHandler = MouseHandler;
});
ace.define("ace/mouse/fold_handler",["require","exports","module"], function(acequire, exports, module) {
"use strict";
function FoldHandler(editor) {
editor.on("click", function(e) {
var position = e.getDocumentPosition();
var session = editor.session;
var fold = session.getFoldAt(position.row, position.column, 1);
if (fold) {
if (e.getAccelKey())
session.removeFold(fold);
else
session.expandFold(fold);
e.stop();
}
});
editor.on("gutterclick", function(e) {
var gutterRegion = editor.renderer.$gutterLayer.getRegion(e);
if (gutterRegion == "foldWidgets") {
var row = e.getDocumentPosition().row;
var session = editor.session;
if (session.foldWidgets && session.foldWidgets[row])
editor.session.onFoldWidgetClick(row, e);
if (!editor.isFocused())
editor.focus();
e.stop();
}
});
editor.on("gutterdblclick", function(e) {
var gutterRegion = editor.renderer.$gutterLayer.getRegion(e);
if (gutterRegion == "foldWidgets") {
var row = e.getDocumentPosition().row;
var session = editor.session;
var data = session.getParentFoldRangeData(row, true);
var range = data.range || data.firstRange;
if (range) {
row = range.start.row;
var fold = session.getFoldAt(row, session.getLine(row).length, 1);
if (fold) {
session.removeFold(fold);
} else {
session.addFold("...", range);
editor.renderer.scrollCursorIntoView({row: range.start.row, column: 0});
}
}
e.stop();
}
});
}
exports.FoldHandler = FoldHandler;
});
ace.define("ace/keyboard/keybinding",["require","exports","module","ace/lib/keys","ace/lib/event"], function(acequire, exports, module) {
"use strict";
var keyUtil = acequire("../lib/keys");
var event = acequire("../lib/event");
var KeyBinding = function(editor) {
this.$editor = editor;
this.$data = {editor: editor};
this.$handlers = [];
this.setDefaultHandler(editor.commands);
};
(function() {
this.setDefaultHandler = function(kb) {
this.removeKeyboardHandler(this.$defaultHandler);
this.$defaultHandler = kb;
this.addKeyboardHandler(kb, 0);
};
this.setKeyboardHandler = function(kb) {
var h = this.$handlers;
if (h[h.length - 1] == kb)
return;
while (h[h.length - 1] && h[h.length - 1] != this.$defaultHandler)
this.removeKeyboardHandler(h[h.length - 1]);
this.addKeyboardHandler(kb, 1);
};
this.addKeyboardHandler = function(kb, pos) {
if (!kb)
return;
if (typeof kb == "function" && !kb.handleKeyboard)
kb.handleKeyboard = kb;
var i = this.$handlers.indexOf(kb);
if (i != -1)
this.$handlers.splice(i, 1);
if (pos == undefined)
this.$handlers.push(kb);
else
this.$handlers.splice(pos, 0, kb);
if (i == -1 && kb.attach)
kb.attach(this.$editor);
};
this.removeKeyboardHandler = function(kb) {
var i = this.$handlers.indexOf(kb);
if (i == -1)
return false;
this.$handlers.splice(i, 1);
kb.detach && kb.detach(this.$editor);
return true;
};
this.getKeyboardHandler = function() {
return this.$handlers[this.$handlers.length - 1];
};
this.getStatusText = function() {
var data = this.$data;
var editor = data.editor;
return this.$handlers.map(function(h) {
return h.getStatusText && h.getStatusText(editor, data) || "";
}).filter(Boolean).join(" ");
};
this.$callKeyboardHandlers = function(hashId, keyString, keyCode, e) {
var toExecute;
var success = false;
var commands = this.$editor.commands;
for (var i = this.$handlers.length; i--;) {
toExecute = this.$handlers[i].handleKeyboard(
this.$data, hashId, keyString, keyCode, e
);
if (!toExecute || !toExecute.command)
continue;
if (toExecute.command == "null") {
success = true;
} else {
success = commands.exec(toExecute.command, this.$editor, toExecute.args, e);
}
if (success && e && hashId != -1 &&
toExecute.passEvent != true && toExecute.command.passEvent != true
) {
event.stopEvent(e);
}
if (success)
break;
}
if (!success && hashId == -1) {
toExecute = {command: "insertstring"};
success = commands.exec("insertstring", this.$editor, keyString);
}
if (success && this.$editor._signal)
this.$editor._signal("keyboardActivity", toExecute);
return success;
};
this.onCommandKey = function(e, hashId, keyCode) {
var keyString = keyUtil.keyCodeToString(keyCode);
this.$callKeyboardHandlers(hashId, keyString, keyCode, e);
};
this.onTextInput = function(text) {
this.$callKeyboardHandlers(-1, text);
};
}).call(KeyBinding.prototype);
exports.KeyBinding = KeyBinding;
});
ace.define("ace/range",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var comparePoints = function(p1, p2) {
return p1.row - p2.row || p1.column - p2.column;
};
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
this.isEqual = function(range) {
return this.start.row === range.start.row &&
this.end.row === range.end.row &&
this.start.column === range.start.column &&
this.end.column === range.end.column;
};
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
};
this.comparePoint = function(p) {
return this.compare(p.row, p.column);
};
this.containsRange = function(range) {
return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
};
this.intersects = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
};
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
};
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
};
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
};
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
};
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
};
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
}
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
};
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
};
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
};
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow)
var end = {row: lastRow + 1, column: 0};
else if (this.end.row < firstRow)
var end = {row: firstRow, column: 0};
if (this.start.row > lastRow)
var start = {row: lastRow + 1, column: 0};
else if (this.start.row < firstRow)
var start = {row: firstRow, column: 0};
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row === this.end.row && this.start.column === this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
else
return new Range(this.start.row, 0, this.end.row, 0)
};
this.toScreenRange = function(session) {
var screenPosStart = session.documentToScreenPosition(this.start);
var screenPosEnd = session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
this.moveBy = function(row, column) {
this.start.row += row;
this.start.column += column;
this.end.row += row;
this.end.column += column;
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
Range.comparePoints = comparePoints;
Range.comparePoints = function(p1, p2) {
return p1.row - p2.row || p1.column - p2.column;
};
exports.Range = Range;
});
ace.define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var lang = acequire("./lib/lang");
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var Range = acequire("./range").Range;
var Selection = function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.lead = this.selectionLead = this.doc.createAnchor(0, 0);
this.anchor = this.selectionAnchor = this.doc.createAnchor(0, 0);
var self = this;
this.lead.on("change", function(e) {
self._emit("changeCursor");
if (!self.$isEmpty)
self._emit("changeSelection");
if (!self.$keepDesiredColumnOnChange && e.old.column != e.value.column)
self.$desiredColumn = null;
});
this.selectionAnchor.on("change", function() {
if (!self.$isEmpty)
self._emit("changeSelection");
});
};
(function() {
oop.implement(this, EventEmitter);
this.isEmpty = function() {
return (this.$isEmpty || (
this.anchor.row == this.lead.row &&
this.anchor.column == this.lead.column
));
};
this.isMultiLine = function() {
if (this.isEmpty()) {
return false;
}
return this.getRange().isMultiLine();
};
this.getCursor = function() {
return this.lead.getPosition();
};
this.setSelectionAnchor = function(row, column) {
this.anchor.setPosition(row, column);
if (this.$isEmpty) {
this.$isEmpty = false;
this._emit("changeSelection");
}
};
this.getSelectionAnchor = function() {
if (this.$isEmpty)
return this.getSelectionLead();
else
return this.anchor.getPosition();
};
this.getSelectionLead = function() {
return this.lead.getPosition();
};
this.shiftSelection = function(columns) {
if (this.$isEmpty) {
this.moveCursorTo(this.lead.row, this.lead.column + columns);
return;
}
var anchor = this.getSelectionAnchor();
var lead = this.getSelectionLead();
var isBackwards = this.isBackwards();
if (!isBackwards || anchor.column !== 0)
this.setSelectionAnchor(anchor.row, anchor.column + columns);
if (isBackwards || lead.column !== 0) {
this.$moveSelection(function() {
this.moveCursorTo(lead.row, lead.column + columns);
});
}
};
this.isBackwards = function() {
var anchor = this.anchor;
var lead = this.lead;
return (anchor.row > lead.row || (anchor.row == lead.row && anchor.column > lead.column));
};
this.getRange = function() {
var anchor = this.anchor;
var lead = this.lead;
if (this.isEmpty())
return Range.fromPoints(lead, lead);
if (this.isBackwards()) {
return Range.fromPoints(lead, anchor);
}
else {
return Range.fromPoints(anchor, lead);
}
};
this.clearSelection = function() {
if (!this.$isEmpty) {
this.$isEmpty = true;
this._emit("changeSelection");
}
};
this.selectAll = function() {
var lastRow = this.doc.getLength() - 1;
this.setSelectionAnchor(0, 0);
this.moveCursorTo(lastRow, this.doc.getLine(lastRow).length);
};
this.setRange =
this.setSelectionRange = function(range, reverse) {
if (reverse) {
this.setSelectionAnchor(range.end.row, range.end.column);
this.selectTo(range.start.row, range.start.column);
} else {
this.setSelectionAnchor(range.start.row, range.start.column);
this.selectTo(range.end.row, range.end.column);
}
if (this.getRange().isEmpty())
this.$isEmpty = true;
this.$desiredColumn = null;
};
this.$moveSelection = function(mover) {
var lead = this.lead;
if (this.$isEmpty)
this.setSelectionAnchor(lead.row, lead.column);
mover.call(this);
};
this.selectTo = function(row, column) {
this.$moveSelection(function() {
this.moveCursorTo(row, column);
});
};
this.selectToPosition = function(pos) {
this.$moveSelection(function() {
this.moveCursorToPosition(pos);
});
};
this.moveTo = function(row, column) {
this.clearSelection();
this.moveCursorTo(row, column);
};
this.moveToPosition = function(pos) {
this.clearSelection();
this.moveCursorToPosition(pos);
};
this.selectUp = function() {
this.$moveSelection(this.moveCursorUp);
};
this.selectDown = function() {
this.$moveSelection(this.moveCursorDown);
};
this.selectRight = function() {
this.$moveSelection(this.moveCursorRight);
};
this.selectLeft = function() {
this.$moveSelection(this.moveCursorLeft);
};
this.selectLineStart = function() {
this.$moveSelection(this.moveCursorLineStart);
};
this.selectLineEnd = function() {
this.$moveSelection(this.moveCursorLineEnd);
};
this.selectFileEnd = function() {
this.$moveSelection(this.moveCursorFileEnd);
};
this.selectFileStart = function() {
this.$moveSelection(this.moveCursorFileStart);
};
this.selectWordRight = function() {
this.$moveSelection(this.moveCursorWordRight);
};
this.selectWordLeft = function() {
this.$moveSelection(this.moveCursorWordLeft);
};
this.getWordRange = function(row, column) {
if (typeof column == "undefined") {
var cursor = row || this.lead;
row = cursor.row;
column = cursor.column;
}
return this.session.getWordRange(row, column);
};
this.selectWord = function() {
this.setSelectionRange(this.getWordRange());
};
this.selectAWord = function() {
var cursor = this.getCursor();
var range = this.session.getAWordRange(cursor.row, cursor.column);
this.setSelectionRange(range);
};
this.getLineRange = function(row, excludeLastChar) {
var rowStart = typeof row == "number" ? row : this.lead.row;
var rowEnd;
var foldLine = this.session.getFoldLine(rowStart);
if (foldLine) {
rowStart = foldLine.start.row;
rowEnd = foldLine.end.row;
} else {
rowEnd = rowStart;
}
if (excludeLastChar === true)
return new Range(rowStart, 0, rowEnd, this.session.getLine(rowEnd).length);
else
return new Range(rowStart, 0, rowEnd + 1, 0);
};
this.selectLine = function() {
this.setSelectionRange(this.getLineRange());
};
this.moveCursorUp = function() {
this.moveCursorBy(-1, 0);
};
this.moveCursorDown = function() {
this.moveCursorBy(1, 0);
};
this.moveCursorLeft = function() {
var cursor = this.lead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
} else if (cursor.column === 0) {
if (cursor.row > 0) {
this.moveCursorTo(cursor.row - 1, this.doc.getLine(cursor.row - 1).length);
}
}
else {
var tabSize = this.session.getTabSize();
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column-tabSize, cursor.column).split(" ").length-1 == tabSize)
this.moveCursorBy(0, -tabSize);
else
this.moveCursorBy(0, -1);
}
};
this.moveCursorRight = function() {
var cursor = this.lead.getPosition(),
fold;
if (fold = this.session.getFoldAt(cursor.row, cursor.column, 1)) {
this.moveCursorTo(fold.end.row, fold.end.column);
}
else if (this.lead.column == this.doc.getLine(this.lead.row).length) {
if (this.lead.row < this.doc.getLength() - 1) {
this.moveCursorTo(this.lead.row + 1, 0);
}
}
else {
var tabSize = this.session.getTabSize();
var cursor = this.lead;
if (this.session.isTabStop(cursor) && this.doc.getLine(cursor.row).slice(cursor.column, cursor.column+tabSize).split(" ").length-1 == tabSize)
this.moveCursorBy(0, tabSize);
else
this.moveCursorBy(0, 1);
}
};
this.moveCursorLineStart = function() {
var row = this.lead.row;
var column = this.lead.column;
var screenRow = this.session.documentToScreenRow(row, column);
var firstColumnPosition = this.session.screenToDocumentPosition(screenRow, 0);
var beforeCursor = this.session.getDisplayLine(
row, null, firstColumnPosition.row,
firstColumnPosition.column
);
var leadingSpace = beforeCursor.match(/^\s*/);
if (leadingSpace[0].length != column && !this.session.$useEmacsStyleLineStart)
firstColumnPosition.column += leadingSpace[0].length;
this.moveCursorToPosition(firstColumnPosition);
};
this.moveCursorLineEnd = function() {
var lead = this.lead;
var lineEnd = this.session.getDocumentLastRowColumnPosition(lead.row, lead.column);
if (this.lead.column == lineEnd.column) {
var line = this.session.getLine(lineEnd.row);
if (lineEnd.column == line.length) {
var textEnd = line.search(/\s+$/);
if (textEnd > 0)
lineEnd.column = textEnd;
}
}
this.moveCursorTo(lineEnd.row, lineEnd.column);
};
this.moveCursorFileEnd = function() {
var row = this.doc.getLength() - 1;
var column = this.doc.getLine(row).length;
this.moveCursorTo(row, column);
};
this.moveCursorFileStart = function() {
this.moveCursorTo(0, 0);
};
this.moveCursorLongWordRight = function() {
var row = this.lead.row;
var column = this.lead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
this.moveCursorTo(fold.end.row, fold.end.column);
return;
}
if (match = this.session.nonTokenRe.exec(rightOfCursor)) {
column += this.session.nonTokenRe.lastIndex;
this.session.nonTokenRe.lastIndex = 0;
rightOfCursor = line.substring(column);
}
if (column >= line.length) {
this.moveCursorTo(row, line.length);
this.moveCursorRight();
if (row < this.doc.getLength() - 1)
this.moveCursorWordRight();
return;
}
if (match = this.session.tokenRe.exec(rightOfCursor)) {
column += this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.moveCursorLongWordLeft = function() {
var row = this.lead.row;
var column = this.lead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1)) {
this.moveCursorTo(fold.start.row, fold.start.column);
return;
}
var str = this.session.getFoldStringAt(row, column, -1);
if (str == null) {
str = this.doc.getLine(row).substring(0, column);
}
var leftOfCursor = lang.stringReverse(str);
var match;
this.session.nonTokenRe.lastIndex = 0;
this.session.tokenRe.lastIndex = 0;
if (match = this.session.nonTokenRe.exec(leftOfCursor)) {
column -= this.session.nonTokenRe.lastIndex;
leftOfCursor = leftOfCursor.slice(this.session.nonTokenRe.lastIndex);
this.session.nonTokenRe.lastIndex = 0;
}
if (column <= 0) {
this.moveCursorTo(row, 0);
this.moveCursorLeft();
if (row > 0)
this.moveCursorWordLeft();
return;
}
if (match = this.session.tokenRe.exec(leftOfCursor)) {
column -= this.session.tokenRe.lastIndex;
this.session.tokenRe.lastIndex = 0;
}
this.moveCursorTo(row, column);
};
this.$shortWordEndIndex = function(rightOfCursor) {
var match, index = 0, ch;
var whitespaceRe = /\s/;
var tokenRe = this.session.tokenRe;
tokenRe.lastIndex = 0;
if (match = this.session.tokenRe.exec(rightOfCursor)) {
index = this.session.tokenRe.lastIndex;
} else {
while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
index ++;
if (index < 1) {
tokenRe.lastIndex = 0;
while ((ch = rightOfCursor[index]) && !tokenRe.test(ch)) {
tokenRe.lastIndex = 0;
index ++;
if (whitespaceRe.test(ch)) {
if (index > 2) {
index--;
break;
} else {
while ((ch = rightOfCursor[index]) && whitespaceRe.test(ch))
index ++;
if (index > 2)
break;
}
}
}
}
}
tokenRe.lastIndex = 0;
return index;
};
this.moveCursorShortWordRight = function() {
var row = this.lead.row;
var column = this.lead.column;
var line = this.doc.getLine(row);
var rightOfCursor = line.substring(column);
var fold = this.session.getFoldAt(row, column, 1);
if (fold)
return this.moveCursorTo(fold.end.row, fold.end.column);
if (column == line.length) {
var l = this.doc.getLength();
do {
row++;
rightOfCursor = this.doc.getLine(row);
} while (row < l && /^\s*$/.test(rightOfCursor));
if (!/^\s+/.test(rightOfCursor))
rightOfCursor = "";
column = 0;
}
var index = this.$shortWordEndIndex(rightOfCursor);
this.moveCursorTo(row, column + index);
};
this.moveCursorShortWordLeft = function() {
var row = this.lead.row;
var column = this.lead.column;
var fold;
if (fold = this.session.getFoldAt(row, column, -1))
return this.moveCursorTo(fold.start.row, fold.start.column);
var line = this.session.getLine(row).substring(0, column);
if (column === 0) {
do {
row--;
line = this.doc.getLine(row);
} while (row > 0 && /^\s*$/.test(line));
column = line.length;
if (!/\s+$/.test(line))
line = "";
}
var leftOfCursor = lang.stringReverse(line);
var index = this.$shortWordEndIndex(leftOfCursor);
return this.moveCursorTo(row, column - index);
};
this.moveCursorWordRight = function() {
if (this.session.$selectLongWords)
this.moveCursorLongWordRight();
else
this.moveCursorShortWordRight();
};
this.moveCursorWordLeft = function() {
if (this.session.$selectLongWords)
this.moveCursorLongWordLeft();
else
this.moveCursorShortWordLeft();
};
this.moveCursorBy = function(rows, chars) {
var screenPos = this.session.documentToScreenPosition(
this.lead.row,
this.lead.column
);
if (chars === 0) {
if (this.$desiredColumn)
screenPos.column = this.$desiredColumn;
else
this.$desiredColumn = screenPos.column;
}
var docPos = this.session.screenToDocumentPosition(screenPos.row + rows, screenPos.column);
if (rows !== 0 && chars === 0 && docPos.row === this.lead.row && docPos.column === this.lead.column) {
if (this.session.lineWidgets && this.session.lineWidgets[docPos.row]) {
if (docPos.row > 0 || rows > 0)
docPos.row++;
}
}
this.moveCursorTo(docPos.row, docPos.column + chars, chars === 0);
};
this.moveCursorToPosition = function(position) {
this.moveCursorTo(position.row, position.column);
};
this.moveCursorTo = function(row, column, keepDesiredColumn) {
var fold = this.session.getFoldAt(row, column, 1);
if (fold) {
row = fold.start.row;
column = fold.start.column;
}
this.$keepDesiredColumnOnChange = true;
this.lead.setPosition(row, column);
this.$keepDesiredColumnOnChange = false;
if (!keepDesiredColumn)
this.$desiredColumn = null;
};
this.moveCursorToScreen = function(row, column, keepDesiredColumn) {
var pos = this.session.screenToDocumentPosition(row, column);
this.moveCursorTo(pos.row, pos.column, keepDesiredColumn);
};
this.detach = function() {
this.lead.detach();
this.anchor.detach();
this.session = this.doc = null;
};
this.fromOrientedRange = function(range) {
this.setSelectionRange(range, range.cursor == range.start);
this.$desiredColumn = range.desiredColumn || this.$desiredColumn;
};
this.toOrientedRange = function(range) {
var r = this.getRange();
if (range) {
range.start.column = r.start.column;
range.start.row = r.start.row;
range.end.column = r.end.column;
range.end.row = r.end.row;
} else {
range = r;
}
range.cursor = this.isBackwards() ? range.start : range.end;
range.desiredColumn = this.$desiredColumn;
return range;
};
this.getRangeOfMovements = function(func) {
var start = this.getCursor();
try {
func(this);
var end = this.getCursor();
return Range.fromPoints(start,end);
} catch(e) {
return Range.fromPoints(start,start);
} finally {
this.moveCursorToPosition(start);
}
};
this.toJSON = function() {
if (this.rangeCount) {
var data = this.ranges.map(function(r) {
var r1 = r.clone();
r1.isBackwards = r.cursor == r.start;
return r1;
});
} else {
var data = this.getRange();
data.isBackwards = this.isBackwards();
}
return data;
};
this.fromJSON = function(data) {
if (data.start == undefined) {
if (this.rangeList) {
this.toSingleRange(data[0]);
for (var i = data.length; i--; ) {
var r = Range.fromPoints(data[i].start, data[i].end);
if (data[i].isBackwards)
r.cursor = r.start;
this.addRange(r, true);
}
return;
} else
data = data[0];
}
if (this.rangeList)
this.toSingleRange(data);
this.setSelectionRange(data, data.isBackwards);
};
this.isEqual = function(data) {
if ((data.length || this.rangeCount) && data.length != this.rangeCount)
return false;
if (!data.length || !this.ranges)
return this.getRange().isEqual(data);
for (var i = this.ranges.length; i--; ) {
if (!this.ranges[i].isEqual(data[i]))
return false;
}
return true;
};
}).call(Selection.prototype);
exports.Selection = Selection;
});
ace.define("ace/tokenizer",["require","exports","module","ace/config"], function(acequire, exports, module) {
"use strict";
var config = acequire("./config");
var MAX_TOKEN_COUNT = 2000;
var Tokenizer = function(rules) {
this.states = rules;
this.regExps = {};
this.matchMappings = {};
for (var key in this.states) {
var state = this.states[key];
var ruleRegExps = [];
var matchTotal = 0;
var mapping = this.matchMappings[key] = {defaultToken: "text"};
var flag = "g";
var splitterRurles = [];
for (var i = 0; i < state.length; i++) {
var rule = state[i];
if (rule.defaultToken)
mapping.defaultToken = rule.defaultToken;
if (rule.caseInsensitive)
flag = "gi";
if (rule.regex == null)
continue;
if (rule.regex instanceof RegExp)
rule.regex = rule.regex.toString().slice(1, -1);
var adjustedregex = rule.regex;
var matchcount = new RegExp("(?:(" + adjustedregex + ")|(.))").exec("a").length - 2;
if (Array.isArray(rule.token)) {
if (rule.token.length == 1 || matchcount == 1) {
rule.token = rule.token[0];
} else if (matchcount - 1 != rule.token.length) {
this.reportError("number of classes and regexp groups doesn't match", {
rule: rule,
groupCount: matchcount - 1
});
rule.token = rule.token[0];
} else {
rule.tokenArray = rule.token;
rule.token = null;
rule.onMatch = this.$arrayTokens;
}
} else if (typeof rule.token == "function" && !rule.onMatch) {
if (matchcount > 1)
rule.onMatch = this.$applyToken;
else
rule.onMatch = rule.token;
}
if (matchcount > 1) {
if (/\\\d/.test(rule.regex)) {
adjustedregex = rule.regex.replace(/\\([0-9]+)/g, function(match, digit) {
return "\\" + (parseInt(digit, 10) + matchTotal + 1);
});
} else {
matchcount = 1;
adjustedregex = this.removeCapturingGroups(rule.regex);
}
if (!rule.splitRegex && typeof rule.token != "string")
splitterRurles.push(rule); // flag will be known only at the very end
}
mapping[matchTotal] = i;
matchTotal += matchcount;
ruleRegExps.push(adjustedregex);
if (!rule.onMatch)
rule.onMatch = null;
}
if (!ruleRegExps.length) {
mapping[0] = 0;
ruleRegExps.push("$");
}
splitterRurles.forEach(function(rule) {
rule.splitRegex = this.createSplitterRegexp(rule.regex, flag);
}, this);
this.regExps[key] = new RegExp("(" + ruleRegExps.join(")|(") + ")|($)", flag);
}
};
(function() {
this.$setMaxTokenCount = function(m) {
MAX_TOKEN_COUNT = m | 0;
};
this.$applyToken = function(str) {
var values = this.splitRegex.exec(str).slice(1);
var types = this.token.apply(this, values);
if (typeof types === "string")
return [{type: types, value: str}];
var tokens = [];
for (var i = 0, l = types.length; i < l; i++) {
if (values[i])
tokens[tokens.length] = {
type: types[i],
value: values[i]
};
}
return tokens;
};
this.$arrayTokens = function(str) {
if (!str)
return [];
var values = this.splitRegex.exec(str);
if (!values)
return "text";
var tokens = [];
var types = this.tokenArray;
for (var i = 0, l = types.length; i < l; i++) {
if (values[i + 1])
tokens[tokens.length] = {
type: types[i],
value: values[i + 1]
};
}
return tokens;
};
this.removeCapturingGroups = function(src) {
var r = src.replace(
/\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,
function(x, y) {return y ? "(?:" : x;}
);
return r;
};
this.createSplitterRegexp = function(src, flag) {
if (src.indexOf("(?=") != -1) {
var stack = 0;
var inChClass = false;
var lastCapture = {};
src.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g, function(
m, esc, parenOpen, parenClose, square, index
) {
if (inChClass) {
inChClass = square != "]";
} else if (square) {
inChClass = true;
} else if (parenClose) {
if (stack == lastCapture.stack) {
lastCapture.end = index+1;
lastCapture.stack = -1;
}
stack--;
} else if (parenOpen) {
stack++;
if (parenOpen.length != 1) {
lastCapture.stack = stack
lastCapture.start = index;
}
}
return m;
});
if (lastCapture.end != null && /^\)*$/.test(src.substr(lastCapture.end)))
src = src.substring(0, lastCapture.start) + src.substr(lastCapture.end);
}
if (src.charAt(0) != "^") src = "^" + src;
if (src.charAt(src.length - 1) != "$") src += "$";
return new RegExp(src, (flag||"").replace("g", ""));
};
this.getLineTokens = function(line, startState) {
if (startState && typeof startState != "string") {
var stack = startState.slice(0);
startState = stack[0];
if (startState === "#tmp") {
stack.shift()
startState = stack.shift()
}
} else
var stack = [];
var currentState = startState || "start";
var state = this.states[currentState];
if (!state) {
currentState = "start";
state = this.states[currentState];
}
var mapping = this.matchMappings[currentState];
var re = this.regExps[currentState];
re.lastIndex = 0;
var match, tokens = [];
var lastIndex = 0;
var matchAttempts = 0;
var token = {type: null, value: ""};
while (match = re.exec(line)) {
var type = mapping.defaultToken;
var rule = null;
var value = match[0];
var index = re.lastIndex;
if (index - value.length > lastIndex) {
var skipped = line.substring(lastIndex, index - value.length);
if (token.type == type) {
token.value += skipped;
} else {
if (token.type)
tokens.push(token);
token = {type: type, value: skipped};
}
}
for (var i = 0; i < match.length-2; i++) {
if (match[i + 1] === undefined)
continue;
rule = state[mapping[i]];
if (rule.onMatch)
type = rule.onMatch(value, currentState, stack);
else
type = rule.token;
if (rule.next) {
if (typeof rule.next == "string") {
currentState = rule.next;
} else {
currentState = rule.next(currentState, stack);
}
state = this.states[currentState];
if (!state) {
this.reportError("state doesn't exist", currentState);
currentState = "start";
state = this.states[currentState];
}
mapping = this.matchMappings[currentState];
lastIndex = index;
re = this.regExps[currentState];
re.lastIndex = index;
}
break;
}
if (value) {
if (typeof type === "string") {
if ((!rule || rule.merge !== false) && token.type === type) {
token.value += value;
} else {
if (token.type)
tokens.push(token);
token = {type: type, value: value};
}
} else if (type) {
if (token.type)
tokens.push(token);
token = {type: null, value: ""};
for (var i = 0; i < type.length; i++)
tokens.push(type[i]);
}
}
if (lastIndex == line.length)
break;
lastIndex = index;
if (matchAttempts++ > MAX_TOKEN_COUNT) {
if (matchAttempts > 2 * line.length) {
this.reportError("infinite loop with in ace tokenizer", {
startState: startState,
line: line
});
}
while (lastIndex < line.length) {
if (token.type)
tokens.push(token);
token = {
value: line.substring(lastIndex, lastIndex += 2000),
type: "overflow"
};
}
currentState = "start";
stack = [];
break;
}
}
if (token.type)
tokens.push(token);
if (stack.length > 1) {
if (stack[0] !== currentState)
stack.unshift("#tmp", currentState);
}
return {
tokens : tokens,
state : stack.length ? stack : currentState
};
};
this.reportError = config.reportError;
}).call(Tokenizer.prototype);
exports.Tokenizer = Tokenizer;
});
ace.define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"], function(acequire, exports, module) {
"use strict";
var lang = acequire("../lib/lang");
var TextHighlightRules = function() {
this.$rules = {
"start" : [{
token : "empty_line",
regex : '^$'
}, {
defaultToken : "text"
}]
};
};
(function() {
this.addRules = function(rules, prefix) {
if (!prefix) {
for (var key in rules)
this.$rules[key] = rules[key];
return;
}
for (var key in rules) {
var state = rules[key];
for (var i = 0; i < state.length; i++) {
var rule = state[i];
if (rule.next || rule.onMatch) {
if (typeof rule.next == "string") {
if (rule.next.indexOf(prefix) !== 0)
rule.next = prefix + rule.next;
}
if (rule.nextState && rule.nextState.indexOf(prefix) !== 0)
rule.nextState = prefix + rule.nextState;
}
}
this.$rules[prefix + key] = state;
}
};
this.getRules = function() {
return this.$rules;
};
this.embedRules = function (HighlightRules, prefix, escapeRules, states, append) {
var embedRules = typeof HighlightRules == "function"
? new HighlightRules().getRules()
: HighlightRules;
if (states) {
for (var i = 0; i < states.length; i++)
states[i] = prefix + states[i];
} else {
states = [];
for (var key in embedRules)
states.push(prefix + key);
}
this.addRules(embedRules, prefix);
if (escapeRules) {
var addRules = Array.prototype[append ? "push" : "unshift"];
for (var i = 0; i < states.length; i++)
addRules.apply(this.$rules[states[i]], lang.deepCopy(escapeRules));
}
if (!this.$embeds)
this.$embeds = [];
this.$embeds.push(prefix);
};
this.getEmbeds = function() {
return this.$embeds;
};
var pushState = function(currentState, stack) {
if (currentState != "start" || stack.length)
stack.unshift(this.nextState, currentState);
return this.nextState;
};
var popState = function(currentState, stack) {
stack.shift();
return stack.shift() || "start";
};
this.normalizeRules = function() {
var id = 0;
var rules = this.$rules;
function processState(key) {
var state = rules[key];
state.processed = true;
for (var i = 0; i < state.length; i++) {
var rule = state[i];
var toInsert = null;
if (Array.isArray(rule)) {
toInsert = rule;
rule = {};
}
if (!rule.regex && rule.start) {
rule.regex = rule.start;
if (!rule.next)
rule.next = [];
rule.next.push({
defaultToken: rule.token
}, {
token: rule.token + ".end",
regex: rule.end || rule.start,
next: "pop"
});
rule.token = rule.token + ".start";
rule.push = true;
}
var next = rule.next || rule.push;
if (next && Array.isArray(next)) {
var stateName = rule.stateName;
if (!stateName) {
stateName = rule.token;
if (typeof stateName != "string")
stateName = stateName[0] || "";
if (rules[stateName])
stateName += id++;
}
rules[stateName] = next;
rule.next = stateName;
processState(stateName);
} else if (next == "pop") {
rule.next = popState;
}
if (rule.push) {
rule.nextState = rule.next || rule.push;
rule.next = pushState;
delete rule.push;
}
if (rule.rules) {
for (var r in rule.rules) {
if (rules[r]) {
if (rules[r].push)
rules[r].push.apply(rules[r], rule.rules[r]);
} else {
rules[r] = rule.rules[r];
}
}
}
var includeName = typeof rule == "string"
? rule
: typeof rule.include == "string"
? rule.include
: "";
if (includeName) {
toInsert = rules[includeName];
}
if (toInsert) {
var args = [i, 1].concat(toInsert);
if (rule.noEscape)
args = args.filter(function(x) {return !x.next;});
state.splice.apply(state, args);
i--;
}
if (rule.keywordMap) {
rule.token = this.createKeywordMapper(
rule.keywordMap, rule.defaultToken || "text", rule.caseInsensitive
);
delete rule.defaultToken;
}
}
}
Object.keys(rules).forEach(processState, this);
};
this.createKeywordMapper = function(map, defaultToken, ignoreCase, splitChar) {
var keywords = Object.create(null);
Object.keys(map).forEach(function(className) {
var a = map[className];
if (ignoreCase)
a = a.toLowerCase();
var list = a.split(splitChar || "|");
for (var i = list.length; i--; )
keywords[list[i]] = className;
});
if (Object.getPrototypeOf(keywords)) {
keywords.__proto__ = null;
}
this.$keywordList = Object.keys(keywords);
map = null;
return ignoreCase
? function(value) {return keywords[value.toLowerCase()] || defaultToken }
: function(value) {return keywords[value] || defaultToken };
};
this.getKeywords = function() {
return this.$keywords;
};
}).call(TextHighlightRules.prototype);
exports.TextHighlightRules = TextHighlightRules;
});
ace.define("ace/mode/behaviour",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var Behaviour = function() {
this.$behaviours = {};
};
(function () {
this.add = function (name, action, callback) {
switch (undefined) {
case this.$behaviours:
this.$behaviours = {};
case this.$behaviours[name]:
this.$behaviours[name] = {};
}
this.$behaviours[name][action] = callback;
}
this.addBehaviours = function (behaviours) {
for (var key in behaviours) {
for (var action in behaviours[key]) {
this.add(key, action, behaviours[key][action]);
}
}
}
this.remove = function (name) {
if (this.$behaviours && this.$behaviours[name]) {
delete this.$behaviours[name];
}
}
this.inherit = function (mode, filter) {
if (typeof mode === "function") {
var behaviours = new mode().getBehaviours(filter);
} else {
var behaviours = mode.getBehaviours(filter);
}
this.addBehaviours(behaviours);
}
this.getBehaviours = function (filter) {
if (!filter) {
return this.$behaviours;
} else {
var ret = {}
for (var i = 0; i < filter.length; i++) {
if (this.$behaviours[filter[i]]) {
ret[filter[i]] = this.$behaviours[filter[i]];
}
}
return ret;
}
}
}).call(Behaviour.prototype);
exports.Behaviour = Behaviour;
});
ace.define("ace/token_iterator",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var TokenIterator = function(session, initialRow, initialColumn) {
this.$session = session;
this.$row = initialRow;
this.$rowTokens = session.getTokens(initialRow);
var token = session.getTokenAt(initialRow, initialColumn);
this.$tokenIndex = token ? token.index : -1;
};
(function() {
this.stepBackward = function() {
this.$tokenIndex -= 1;
while (this.$tokenIndex < 0) {
this.$row -= 1;
if (this.$row < 0) {
this.$row = 0;
return null;
}
this.$rowTokens = this.$session.getTokens(this.$row);
this.$tokenIndex = this.$rowTokens.length - 1;
}
return this.$rowTokens[this.$tokenIndex];
};
this.stepForward = function() {
this.$tokenIndex += 1;
var rowCount;
while (this.$tokenIndex >= this.$rowTokens.length) {
this.$row += 1;
if (!rowCount)
rowCount = this.$session.getLength();
if (this.$row >= rowCount) {
this.$row = rowCount - 1;
return null;
}
this.$rowTokens = this.$session.getTokens(this.$row);
this.$tokenIndex = 0;
}
return this.$rowTokens[this.$tokenIndex];
};
this.getCurrentToken = function () {
return this.$rowTokens[this.$tokenIndex];
};
this.getCurrentTokenRow = function () {
return this.$row;
};
this.getCurrentTokenColumn = function() {
var rowTokens = this.$rowTokens;
var tokenIndex = this.$tokenIndex;
var column = rowTokens[tokenIndex].start;
if (column !== undefined)
return column;
column = 0;
while (tokenIndex > 0) {
tokenIndex -= 1;
column += rowTokens[tokenIndex].value.length;
}
return column;
};
this.getCurrentTokenPosition = function() {
return {row: this.$row, column: this.getCurrentTokenColumn()};
};
}).call(TokenIterator.prototype);
exports.TokenIterator = TokenIterator;
});
ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../../lib/oop");
var Behaviour = acequire("../behaviour").Behaviour;
var TokenIterator = acequire("../../token_iterator").TokenIterator;
var lang = acequire("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.index;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var getWrapped = function(selection, selected, opening, closing) {
var rowDiff = selection.end.row - selection.start.row;
return {
text: opening + selected + closing,
selection: [
0,
selection.start.column + 1,
rowDiff,
selection.end.column + (rowDiff ? 0 : 1)
]
};
};
var CstyleBehaviour = function() {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '{', '}');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '(', ')');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, '[', ']');
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
if (text == '"' || text == "'") {
if (this.lineCommentStart && this.lineCommentStart.indexOf(text) != -1)
return;
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return getWrapped(selection, selected, quote, quote);
} else if (!selected) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var token = session.getTokenAt(cursor.row, cursor.column);
var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
if (leftChar == "\\" && token && /escape/.test(token.type))
return null;
var stringBefore = token && /string|escape/.test(token.type);
var stringAfter = !rightToken || /string|escape/.test(rightToken.type);
var pair;
if (rightChar == quote) {
pair = stringBefore !== stringAfter;
if (pair && /string\.end/.test(rightToken.type))
pair = false;
} else {
if (stringBefore && !stringAfter)
return null; // wrap string with different quote
if (stringBefore && stringAfter)
return null; // do not pair quotes inside strings
var wordRe = session.$mode.tokenRe;
wordRe.lastIndex = 0;
var isWordBefore = wordRe.test(leftChar);
wordRe.lastIndex = 0;
var isWordAfter = wordRe.test(leftChar);
if (isWordBefore || isWordAfter)
return null; // before or after alphanumeric
if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
return null; // there is rightChar and it isn't closing
pair = true;
}
return {
text: pair ? quote + quote : "",
selection: [1,1]
};
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define("ace/unicode",["require","exports","module"], function(acequire, exports, module) {
"use strict";
exports.packages = {};
addUnicodePackage({
L: "0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
Ll: "0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",
Lu: "0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",
Lt: "01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",
Lm: "02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",
Lo: "01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",
M: "0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",
Mn: "0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",
Mc: "0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",
Me: "0488048906DE20DD-20E020E2-20E4A670-A672",
N: "0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nd: "0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",
Nl: "16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",
No: "00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",
P: "0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",
Pd: "002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",
Ps: "0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",
Pe: "0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",
Pi: "00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",
Pf: "00BB2019201D203A2E032E052E0A2E0D2E1D2E21",
Pc: "005F203F20402054FE33FE34FE4D-FE4FFF3F",
Po: "0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",
S: "0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",
Sm: "002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",
Sc: "002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",
Sk: "005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",
So: "00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",
Z: "002000A01680180E2000-200A20282029202F205F3000",
Zs: "002000A01680180E2000-200A202F205F3000",
Zl: "2028",
Zp: "2029",
C: "0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",
Cc: "0000-001F007F-009F",
Cf: "00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",
Co: "E000-F8FF",
Cs: "D800-DFFF",
Cn: "03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"
});
function addUnicodePackage (pack) {
var codePoint = /\w{4}/g;
for (var name in pack)
exports.packages[name] = pack[name].replace(codePoint, "\\u$&");
}
});
ace.define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour/cstyle","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"], function(acequire, exports, module) {
"use strict";
var Tokenizer = acequire("../tokenizer").Tokenizer;
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour;
var unicode = acequire("../unicode");
var lang = acequire("../lib/lang");
var TokenIterator = acequire("../token_iterator").TokenIterator;
var Range = acequire("../range").Range;
var Mode = function() {
this.HighlightRules = TextHighlightRules;
};
(function() {
this.$defaultBehaviour = new CstyleBehaviour();
this.tokenRe = new RegExp("^["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]+", "g"
);
this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]|\\s])+", "g"
);
this.getTokenizer = function() {
if (!this.$tokenizer) {
this.$highlightRules = this.$highlightRules || new this.HighlightRules(this.$highlightRuleConfig);
this.$tokenizer = new Tokenizer(this.$highlightRules.getRules());
}
return this.$tokenizer;
};
this.lineCommentStart = "";
this.blockComment = "";
this.toggleCommentLines = function(state, session, startRow, endRow) {
var doc = session.doc;
var ignoreBlankLines = true;
var shouldRemove = true;
var minIndent = Infinity;
var tabSize = session.getTabSize();
var insertAtTabStop = false;
if (!this.lineCommentStart) {
if (!this.blockComment)
return false;
var lineCommentStart = this.blockComment.start;
var lineCommentEnd = this.blockComment.end;
var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")");
var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$");
var comment = function(line, i) {
if (testRemove(line, i))
return;
if (!ignoreBlankLines || /\S/.test(line)) {
doc.insertInLine({row: i, column: line.length}, lineCommentEnd);
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
}
};
var uncomment = function(line, i) {
var m;
if (m = line.match(regexpEnd))
doc.removeInLine(i, line.length - m[0].length, line.length);
if (m = line.match(regexpStart))
doc.removeInLine(i, m[1].length, m[0].length);
};
var testRemove = function(line, row) {
if (regexpStart.test(line))
return true;
var tokens = session.getTokens(row);
for (var i = 0; i < tokens.length; i++) {
if (tokens[i].type === "comment")
return true;
}
};
} else {
if (Array.isArray(this.lineCommentStart)) {
var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|");
var lineCommentStart = this.lineCommentStart[0];
} else {
var regexpStart = lang.escapeRegExp(this.lineCommentStart);
var lineCommentStart = this.lineCommentStart;
}
regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?");
insertAtTabStop = session.getUseSoftTabs();
var uncomment = function(line, i) {
var m = line.match(regexpStart);
if (!m) return;
var start = m[1].length, end = m[0].length;
if (!shouldInsertSpace(line, start, end) && m[0][end - 1] == " ")
end--;
doc.removeInLine(i, start, end);
};
var commentWithSpace = lineCommentStart + " ";
var comment = function(line, i) {
if (!ignoreBlankLines || /\S/.test(line)) {
if (shouldInsertSpace(line, minIndent, minIndent))
doc.insertInLine({row: i, column: minIndent}, commentWithSpace);
else
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
}
};
var testRemove = function(line, i) {
return regexpStart.test(line);
};
var shouldInsertSpace = function(line, before, after) {
var spaces = 0;
while (before-- && line.charAt(before) == " ")
spaces++;
if (spaces % tabSize != 0)
return false;
var spaces = 0;
while (line.charAt(after++) == " ")
spaces++;
if (tabSize > 2)
return spaces % tabSize != tabSize - 1;
else
return spaces % tabSize == 0;
return true;
};
}
function iter(fun) {
for (var i = startRow; i <= endRow; i++)
fun(doc.getLine(i), i);
}
var minEmptyLength = Infinity;
iter(function(line, i) {
var indent = line.search(/\S/);
if (indent !== -1) {
if (indent < minIndent)
minIndent = indent;
if (shouldRemove && !testRemove(line, i))
shouldRemove = false;
} else if (minEmptyLength > line.length) {
minEmptyLength = line.length;
}
});
if (minIndent == Infinity) {
minIndent = minEmptyLength;
ignoreBlankLines = false;
shouldRemove = false;
}
if (insertAtTabStop && minIndent % tabSize != 0)
minIndent = Math.floor(minIndent / tabSize) * tabSize;
iter(shouldRemove ? uncomment : comment);
};
this.toggleBlockComment = function(state, session, range, cursor) {
var comment = this.blockComment;
if (!comment)
return;
if (!comment.start && comment[0])
comment = comment[0];
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
var sel = session.selection;
var initialRange = session.selection.toOrientedRange();
var startRow, colDiff;
if (token && /comment/.test(token.type)) {
var startRange, endRange;
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.start);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
startRange = new Range(row, column, row, column + comment.start.length);
break;
}
token = iterator.stepBackward();
}
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.end);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
endRange = new Range(row, column, row, column + comment.end.length);
break;
}
token = iterator.stepForward();
}
if (endRange)
session.remove(endRange);
if (startRange) {
session.remove(startRange);
startRow = startRange.start.row;
colDiff = -comment.start.length;
}
} else {
colDiff = comment.start.length;
startRow = range.start.row;
session.insert(range.end, comment.end);
session.insert(range.start, comment.start);
}
if (initialRange.start.row == startRow)
initialRange.start.column += colDiff;
if (initialRange.end.row == startRow)
initialRange.end.column += colDiff;
session.selection.fromOrientedRange(initialRange);
};
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.checkOutdent = function(state, line, input) {
return false;
};
this.autoOutdent = function(state, doc, row) {
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
this.createWorker = function(session) {
return null;
};
this.createModeDelegates = function (mapping) {
this.$embeds = [];
this.$modes = {};
for (var i in mapping) {
if (mapping[i]) {
this.$embeds.push(i);
this.$modes[i] = new mapping[i]();
}
}
var delegations = ["toggleBlockComment", "toggleCommentLines", "getNextLineIndent",
"checkOutdent", "autoOutdent", "transformAction", "getCompletions"];
for (var i = 0; i < delegations.length; i++) {
(function(scope) {
var functionName = delegations[i];
var defaultHandler = scope[functionName];
scope[delegations[i]] = function() {
return this.$delegator(functionName, arguments, defaultHandler);
};
}(this));
}
};
this.$delegator = function(method, args, defaultHandler) {
var state = args[0];
if (typeof state != "string")
state = state[0];
for (var i = 0; i < this.$embeds.length; i++) {
if (!this.$modes[this.$embeds[i]]) continue;
var split = state.split(this.$embeds[i]);
if (!split[0] && split[1]) {
args[0] = split[1];
var mode = this.$modes[this.$embeds[i]];
return mode[method].apply(mode, args);
}
}
var ret = defaultHandler.apply(this, args);
return defaultHandler ? ret : undefined;
};
this.transformAction = function(state, action, editor, session, param) {
if (this.$behaviour) {
var behaviours = this.$behaviour.getBehaviours();
for (var key in behaviours) {
if (behaviours[key][action]) {
var ret = behaviours[key][action].apply(this, arguments);
if (ret) {
return ret;
}
}
}
}
};
this.getKeywords = function(append) {
if (!this.completionKeywords) {
var rules = this.$tokenizer.rules;
var completionKeywords = [];
for (var rule in rules) {
var ruleItr = rules[rule];
for (var r = 0, l = ruleItr.length; r < l; r++) {
if (typeof ruleItr[r].token === "string") {
if (/keyword|support|storage/.test(ruleItr[r].token))
completionKeywords.push(ruleItr[r].regex);
}
else if (typeof ruleItr[r].token === "object") {
for (var a = 0, aLength = ruleItr[r].token.length; a < aLength; a++) {
if (/keyword|support|storage/.test(ruleItr[r].token[a])) {
var rule = ruleItr[r].regex.match(/\(.+?\)/g)[a];
completionKeywords.push(rule.substr(1, rule.length - 2));
}
}
}
}
}
this.completionKeywords = completionKeywords;
}
if (!append)
return this.$keywordList;
return completionKeywords.concat(this.$keywordList || []);
};
this.$createKeywordList = function() {
if (!this.$highlightRules)
this.getTokenizer();
return this.$keywordList = this.$highlightRules.$keywordList || [];
};
this.getCompletions = function(state, session, pos, prefix) {
var keywords = this.$keywordList || this.$createKeywordList();
return keywords.map(function(word) {
return {
name: word,
value: word,
score: 0,
meta: "keyword"
};
});
};
this.$id = "ace/mode/text";
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define("ace/apply_delta",["require","exports","module"], function(acequire, exports, module) {
"use strict";
function throwDeltaError(delta, errorText){
console.log("Invalid Delta:", delta);
throw "Invalid Delta: " + errorText;
}
function positionInDocument(docLines, position) {
return position.row >= 0 && position.row < docLines.length &&
position.column >= 0 && position.column <= docLines[position.row].length;
}
function validateDelta(docLines, delta) {
if (delta.action != "insert" && delta.action != "remove")
throwDeltaError(delta, "delta.action must be 'insert' or 'remove'");
if (!(delta.lines instanceof Array))
throwDeltaError(delta, "delta.lines must be an Array");
if (!delta.start || !delta.end)
throwDeltaError(delta, "delta.start/end must be an present");
var start = delta.start;
if (!positionInDocument(docLines, delta.start))
throwDeltaError(delta, "delta.start must be contained in document");
var end = delta.end;
if (delta.action == "remove" && !positionInDocument(docLines, end))
throwDeltaError(delta, "delta.end must contained in document for 'remove' actions");
var numRangeRows = end.row - start.row;
var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0));
if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars)
throwDeltaError(delta, "delta.range must match delta lines");
}
exports.applyDelta = function(docLines, delta, doNotValidate) {
var row = delta.start.row;
var startColumn = delta.start.column;
var line = docLines[row] || "";
switch (delta.action) {
case "insert":
var lines = delta.lines;
if (lines.length === 1) {
docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn);
} else {
var args = [row, 1].concat(delta.lines);
docLines.splice.apply(docLines, args);
docLines[row] = line.substring(0, startColumn) + docLines[row];
docLines[row + delta.lines.length - 1] += line.substring(startColumn);
}
break;
case "remove":
var endColumn = delta.end.column;
var endRow = delta.end.row;
if (row === endRow) {
docLines[row] = line.substring(0, startColumn) + line.substring(endColumn);
} else {
docLines.splice(
row, endRow - row + 1,
line.substring(0, startColumn) + docLines[endRow].substring(endColumn)
);
}
break;
}
}
});
ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var Anchor = exports.Anchor = function(doc, row, column) {
this.$onChange = this.onChange.bind(this);
this.attach(doc);
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.$insertRight = false;
this.onChange = function(delta) {
if (delta.start.row == delta.end.row && delta.start.row != this.row)
return;
if (delta.start.row > this.row)
return;
var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight);
this.setPosition(point.row, point.column, true);
};
function $pointsInOrder(point1, point2, equalPointsInOrder) {
var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column;
return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter);
}
function $getTransformedPoint(delta, point, moveIfEqual) {
var deltaIsInsert = delta.action == "insert";
var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row);
var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column);
var deltaStart = delta.start;
var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range.
if ($pointsInOrder(point, deltaStart, moveIfEqual)) {
return {
row: point.row,
column: point.column
};
}
if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) {
return {
row: point.row + deltaRowShift,
column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0)
};
}
return {
row: deltaStart.row,
column: deltaStart.column
};
}
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
} else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._signal("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.attach = function(doc) {
this.document = doc || this.document;
this.document.on("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var applyDelta = acequire("./apply_delta").applyDelta;
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var Range = acequire("./range").Range;
var Anchor = acequire("./anchor").Anchor;
var Document = function(textOrLines) {
this.$lines = [""];
if (textOrLines.length === 0) {
this.$lines = [""];
} else if (Array.isArray(textOrLines)) {
this.insertMergedLines({row: 0, column: 0}, textOrLines);
} else {
this.insert({row: 0, column:0}, textOrLines);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength() - 1;
this.remove(new Range(0, 0, len, this.getLine(len).length));
this.insert({row: 0, column: 0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
if ("aaa".split(/a/).length === 0) {
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
};
} else {
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
}
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r\n|\r|\n)/m);
this.$autoNewLine = match ? match[1] : "\n";
this._signal("changeNewLineMode");
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
default:
return this.$autoNewLine || "\n";
}
};
this.$autoNewLine = "";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode)
return;
this.$newLineMode = newLineMode;
this._signal("changeNewLineMode");
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
return this.getLinesForRange(range).join(this.getNewLineCharacter());
};
this.getLinesForRange = function(range) {
var lines;
if (range.start.row === range.end.row) {
lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)];
} else {
lines = this.getLines(range.start.row, range.end.row);
lines[0] = (lines[0] || "").substring(range.start.column);
var l = lines.length - 1;
if (range.end.row - range.start.row == l)
lines[l] = lines[l].substring(0, range.end.column);
}
return lines;
};
this.insertLines = function(row, lines) {
console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead.");
return this.insertFullLines(row, lines);
};
this.removeLines = function(firstRow, lastRow) {
console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead.");
return this.removeFullLines(firstRow, lastRow);
};
this.insertNewLine = function(position) {
console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.");
return this.insertMergedLines(position, ["", ""]);
};
this.insert = function(position, text) {
if (this.getLength() <= 1)
this.$detectNewLine(text);
return this.insertMergedLines(position, this.$split(text));
};
this.insertInLine = function(position, text) {
var start = this.clippedPos(position.row, position.column);
var end = this.pos(position.row, position.column + text.length);
this.applyDelta({
start: start,
end: end,
action: "insert",
lines: [text]
}, true);
return this.clonePos(end);
};
this.clippedPos = function(row, column) {
var length = this.getLength();
if (row === undefined) {
row = length;
} else if (row < 0) {
row = 0;
} else if (row >= length) {
row = length - 1;
column = undefined;
}
var line = this.getLine(row);
if (column == undefined)
column = line.length;
column = Math.min(Math.max(column, 0), line.length);
return {row: row, column: column};
};
this.clonePos = function(pos) {
return {row: pos.row, column: pos.column};
};
this.pos = function(row, column) {
return {row: row, column: column};
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length - 1).length;
} else {
position.row = Math.max(0, position.row);
position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length);
}
return position;
};
this.insertFullLines = function(row, lines) {
row = Math.min(Math.max(row, 0), this.getLength());
var column = 0;
if (row < this.getLength()) {
lines = lines.concat([""]);
column = 0;
} else {
lines = [""].concat(lines);
row--;
column = this.$lines[row].length;
}
this.insertMergedLines({row: row, column: column}, lines);
};
this.insertMergedLines = function(position, lines) {
var start = this.clippedPos(position.row, position.column);
var end = {
row: start.row + lines.length - 1,
column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length
};
this.applyDelta({
start: start,
end: end,
action: "insert",
lines: lines
});
return this.clonePos(end);
};
this.remove = function(range) {
var start = this.clippedPos(range.start.row, range.start.column);
var end = this.clippedPos(range.end.row, range.end.column);
this.applyDelta({
start: start,
end: end,
action: "remove",
lines: this.getLinesForRange({start: start, end: end})
});
return this.clonePos(start);
};
this.removeInLine = function(row, startColumn, endColumn) {
var start = this.clippedPos(row, startColumn);
var end = this.clippedPos(row, endColumn);
this.applyDelta({
start: start,
end: end,
action: "remove",
lines: this.getLinesForRange({start: start, end: end})
}, true);
return this.clonePos(start);
};
this.removeFullLines = function(firstRow, lastRow) {
firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1);
lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1);
var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0;
var deleteLastNewLine = lastRow < this.getLength() - 1;
var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow );
var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 );
var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow );
var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length );
var range = new Range(startRow, startCol, endRow, endCol);
var deletedLines = this.$lines.slice(firstRow, lastRow + 1);
this.applyDelta({
start: range.start,
end: range.end,
action: "remove",
lines: this.getLinesForRange(range)
});
return deletedLines;
};
this.removeNewLine = function(row) {
if (row < this.getLength() - 1 && row >= 0) {
this.applyDelta({
start: this.pos(row, this.getLine(row).length),
end: this.pos(row + 1, 0),
action: "remove",
lines: ["", ""]
});
}
};
this.replace = function(range, text) {
if (!(range instanceof Range))
range = Range.fromPoints(range.start, range.end);
if (text.length === 0 && range.isEmpty())
return range.start;
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
var end;
if (text) {
end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
this.applyDelta(deltas[i]);
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
this.revertDelta(deltas[i]);
}
};
this.applyDelta = function(delta, doNotValidate) {
var isInsert = delta.action == "insert";
if (isInsert ? delta.lines.length <= 1 && !delta.lines[0]
: !Range.comparePoints(delta.start, delta.end)) {
return;
}
if (isInsert && delta.lines.length > 20000)
this.$splitAndapplyLargeDelta(delta, 20000);
applyDelta(this.$lines, delta, doNotValidate);
this._signal("change", delta);
};
this.$splitAndapplyLargeDelta = function(delta, MAX) {
var lines = delta.lines;
var l = lines.length;
var row = delta.start.row;
var column = delta.start.column;
var from = 0, to = 0;
do {
from = to;
to += MAX - 1;
var chunk = lines.slice(from, to);
if (to > l) {
delta.lines = chunk;
delta.start.row = row + from;
delta.start.column = column;
break;
}
chunk.push("");
this.applyDelta({
start: this.pos(row + from, column),
end: this.pos(row + to, column = 0),
action: delta.action,
lines: chunk
}, true);
} while(true);
};
this.revertDelta = function(delta) {
this.applyDelta({
start: this.clonePos(delta.start),
end: this.clonePos(delta.end),
action: (delta.action == "insert" ? "remove" : "insert"),
lines: delta.lines.slice()
});
};
this.indexToPosition = function(index, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
for (var i = startRow || 0, l = lines.length; i < l; i++) {
index -= lines[i].length + newlineLength;
if (index < 0)
return {row: i, column: index + lines[i].length + newlineLength};
}
return {row: l-1, column: lines[l-1].length};
};
this.positionToIndex = function(pos, startRow) {
var lines = this.$lines || this.getAllLines();
var newlineLength = this.getNewLineCharacter().length;
var index = 0;
var row = Math.min(pos.row, lines.length);
for (var i = startRow || 0; i < row; ++i)
index += lines[i].length + newlineLength;
return index + pos.column;
};
}).call(Document.prototype);
exports.Document = Document;
});
ace.define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var BackgroundTokenizer = function(tokenizer, editor) {
this.running = false;
this.lines = [];
this.states = [];
this.currentLine = 0;
this.tokenizer = tokenizer;
var self = this;
this.$worker = function() {
if (!self.running) { return; }
var workerStart = new Date();
var currentLine = self.currentLine;
var endLine = -1;
var doc = self.doc;
var startLine = currentLine;
while (self.lines[currentLine])
currentLine++;
var len = doc.getLength();
var processedLines = 0;
self.running = false;
while (currentLine < len) {
self.$tokenizeRow(currentLine);
endLine = currentLine;
do {
currentLine++;
} while (self.lines[currentLine]);
processedLines ++;
if ((processedLines % 5 === 0) && (new Date() - workerStart) > 20) {
self.running = setTimeout(self.$worker, 20);
break;
}
}
self.currentLine = currentLine;
if (startLine <= endLine)
self.fireUpdateEvent(startLine, endLine);
};
};
(function(){
oop.implement(this, EventEmitter);
this.setTokenizer = function(tokenizer) {
this.tokenizer = tokenizer;
this.lines = [];
this.states = [];
this.start(0);
};
this.setDocument = function(doc) {
this.doc = doc;
this.lines = [];
this.states = [];
this.stop();
};
this.fireUpdateEvent = function(firstRow, lastRow) {
var data = {
first: firstRow,
last: lastRow
};
this._signal("update", {data: data});
};
this.start = function(startRow) {
this.currentLine = Math.min(startRow || 0, this.currentLine, this.doc.getLength());
this.lines.splice(this.currentLine, this.lines.length);
this.states.splice(this.currentLine, this.states.length);
this.stop();
this.running = setTimeout(this.$worker, 700);
};
this.scheduleStart = function() {
if (!this.running)
this.running = setTimeout(this.$worker, 700);
}
this.$updateOnChange = function(delta) {
var startRow = delta.start.row;
var len = delta.end.row - startRow;
if (len === 0) {
this.lines[startRow] = null;
} else if (delta.action == "remove") {
this.lines.splice(startRow, len + 1, null);
this.states.splice(startRow, len + 1, null);
} else {
var args = Array(len + 1);
args.unshift(startRow, 1);
this.lines.splice.apply(this.lines, args);
this.states.splice.apply(this.states, args);
}
this.currentLine = Math.min(startRow, this.currentLine, this.doc.getLength());
this.stop();
};
this.stop = function() {
if (this.running)
clearTimeout(this.running);
this.running = false;
};
this.getTokens = function(row) {
return this.lines[row] || this.$tokenizeRow(row);
};
this.getState = function(row) {
if (this.currentLine == row)
this.$tokenizeRow(row);
return this.states[row] || "start";
};
this.$tokenizeRow = function(row) {
var line = this.doc.getLine(row);
var state = this.states[row - 1];
var data = this.tokenizer.getLineTokens(line, state, row);
if (this.states[row] + "" !== data.state + "") {
this.states[row] = data.state;
this.lines[row + 1] = null;
if (this.currentLine > row + 1)
this.currentLine = row + 1;
} else if (this.currentLine == row) {
this.currentLine = row + 1;
}
return this.lines[row] = data.tokens;
};
}).call(BackgroundTokenizer.prototype);
exports.BackgroundTokenizer = BackgroundTokenizer;
});
ace.define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) {
"use strict";
var lang = acequire("./lib/lang");
var oop = acequire("./lib/oop");
var Range = acequire("./range").Range;
var SearchHighlight = function(regExp, clazz, type) {
this.setRegexp(regExp);
this.clazz = clazz;
this.type = type || "text";
};
(function() {
this.MAX_RANGES = 500;
this.setRegexp = function(regExp) {
if (this.regExp+"" == regExp+"")
return;
this.regExp = regExp;
this.cache = [];
};
this.update = function(html, markerLayer, session, config) {
if (!this.regExp)
return;
var start = config.firstRow, end = config.lastRow;
for (var i = start; i <= end; i++) {
var ranges = this.cache[i];
if (ranges == null) {
ranges = lang.getMatchOffsets(session.getLine(i), this.regExp);
if (ranges.length > this.MAX_RANGES)
ranges = ranges.slice(0, this.MAX_RANGES);
ranges = ranges.map(function(match) {
return new Range(i, match.offset, i, match.offset + match.length);
});
this.cache[i] = ranges.length ? ranges : "";
}
for (var j = ranges.length; j --; ) {
markerLayer.drawSingleLineMarker(
html, ranges[j].toScreenRange(session), this.clazz, config);
}
}
};
}).call(SearchHighlight.prototype);
exports.SearchHighlight = SearchHighlight;
});
ace.define("ace/edit_session/fold_line",["require","exports","module","ace/range"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
function FoldLine(foldData, folds) {
this.foldData = foldData;
if (Array.isArray(folds)) {
this.folds = folds;
} else {
folds = this.folds = [ folds ];
}
var last = folds[folds.length - 1];
this.range = new Range(folds[0].start.row, folds[0].start.column,
last.end.row, last.end.column);
this.start = this.range.start;
this.end = this.range.end;
this.folds.forEach(function(fold) {
fold.setFoldLine(this);
}, this);
}
(function() {
this.shiftRow = function(shift) {
this.start.row += shift;
this.end.row += shift;
this.folds.forEach(function(fold) {
fold.start.row += shift;
fold.end.row += shift;
});
};
this.addFold = function(fold) {
if (fold.sameRow) {
if (fold.start.row < this.startRow || fold.endRow > this.endRow) {
throw new Error("Can't add a fold to this FoldLine as it has no connection");
}
this.folds.push(fold);
this.folds.sort(function(a, b) {
return -a.range.compareEnd(b.start.row, b.start.column);
});
if (this.range.compareEnd(fold.start.row, fold.start.column) > 0) {
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (this.range.compareStart(fold.end.row, fold.end.column) < 0) {
this.start.row = fold.start.row;
this.start.column = fold.start.column;
}
} else if (fold.start.row == this.end.row) {
this.folds.push(fold);
this.end.row = fold.end.row;
this.end.column = fold.end.column;
} else if (fold.end.row == this.start.row) {
this.folds.unshift(fold);
this.start.row = fold.start.row;
this.start.column = fold.start.column;
} else {
throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");
}
fold.foldLine = this;
};
this.containsRow = function(row) {
return row >= this.start.row && row <= this.end.row;
};
this.walk = function(callback, endRow, endColumn) {
var lastEnd = 0,
folds = this.folds,
fold,
cmp, stop, isNewRow = true;
if (endRow == null) {
endRow = this.end.row;
endColumn = this.end.column;
}
for (var i = 0; i < folds.length; i++) {
fold = folds[i];
cmp = fold.range.compareStart(endRow, endColumn);
if (cmp == -1) {
callback(null, endRow, endColumn, lastEnd, isNewRow);
return;
}
stop = callback(null, fold.start.row, fold.start.column, lastEnd, isNewRow);
stop = !stop && callback(fold.placeholder, fold.start.row, fold.start.column, lastEnd);
if (stop || cmp === 0) {
return;
}
isNewRow = !fold.sameRow;
lastEnd = fold.end.column;
}
callback(null, endRow, endColumn, lastEnd, isNewRow);
};
this.getNextFoldTo = function(row, column) {
var fold, cmp;
for (var i = 0; i < this.folds.length; i++) {
fold = this.folds[i];
cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
return {
fold: fold,
kind: "after"
};
} else if (cmp === 0) {
return {
fold: fold,
kind: "inside"
};
}
}
return null;
};
this.addRemoveChars = function(row, column, len) {
var ret = this.getNextFoldTo(row, column),
fold, folds;
if (ret) {
fold = ret.fold;
if (ret.kind == "inside"
&& fold.start.column != column
&& fold.start.row != row)
{
window.console && window.console.log(row, column, fold);
} else if (fold.start.row == row) {
folds = this.folds;
var i = folds.indexOf(fold);
if (i === 0) {
this.start.column += len;
}
for (i; i < folds.length; i++) {
fold = folds[i];
fold.start.column += len;
if (!fold.sameRow) {
return;
}
fold.end.column += len;
}
this.end.column += len;
}
}
};
this.split = function(row, column) {
var pos = this.getNextFoldTo(row, column);
if (!pos || pos.kind == "inside")
return null;
var fold = pos.fold;
var folds = this.folds;
var foldData = this.foldData;
var i = folds.indexOf(fold);
var foldBefore = folds[i - 1];
this.end.row = foldBefore.end.row;
this.end.column = foldBefore.end.column;
folds = folds.splice(i, folds.length - i);
var newFoldLine = new FoldLine(foldData, folds);
foldData.splice(foldData.indexOf(this) + 1, 0, newFoldLine);
return newFoldLine;
};
this.merge = function(foldLineNext) {
var folds = foldLineNext.folds;
for (var i = 0; i < folds.length; i++) {
this.addFold(folds[i]);
}
var foldData = this.foldData;
foldData.splice(foldData.indexOf(foldLineNext), 1);
};
this.toString = function() {
var ret = [this.range.toString() + ": [" ];
this.folds.forEach(function(fold) {
ret.push(" " + fold.toString());
});
ret.push("]");
return ret.join("\n");
};
this.idxToPosition = function(idx) {
var lastFoldEndColumn = 0;
for (var i = 0; i < this.folds.length; i++) {
var fold = this.folds[i];
idx -= fold.start.column - lastFoldEndColumn;
if (idx < 0) {
return {
row: fold.start.row,
column: fold.start.column + idx
};
}
idx -= fold.placeholder.length;
if (idx < 0) {
return fold.start;
}
lastFoldEndColumn = fold.end.column;
}
return {
row: this.end.row,
column: this.end.column + idx
};
};
}).call(FoldLine.prototype);
exports.FoldLine = FoldLine;
});
ace.define("ace/range_list",["require","exports","module","ace/range"], function(acequire, exports, module) {
"use strict";
var Range = acequire("./range").Range;
var comparePoints = Range.comparePoints;
var RangeList = function() {
this.ranges = [];
};
(function() {
this.comparePoints = comparePoints;
this.pointIndex = function(pos, excludeEdges, startIndex) {
var list = this.ranges;
for (var i = startIndex || 0; i < list.length; i++) {
var range = list[i];
var cmpEnd = comparePoints(pos, range.end);
if (cmpEnd > 0)
continue;
var cmpStart = comparePoints(pos, range.start);
if (cmpEnd === 0)
return excludeEdges && cmpStart !== 0 ? -i-2 : i;
if (cmpStart > 0 || (cmpStart === 0 && !excludeEdges))
return i;
return -i-1;
}
return -i - 1;
};
this.add = function(range) {
var excludeEdges = !range.isEmpty();
var startIndex = this.pointIndex(range.start, excludeEdges);
if (startIndex < 0)
startIndex = -startIndex - 1;
var endIndex = this.pointIndex(range.end, excludeEdges, startIndex);
if (endIndex < 0)
endIndex = -endIndex - 1;
else
endIndex++;
return this.ranges.splice(startIndex, endIndex - startIndex, range);
};
this.addList = function(list) {
var removed = [];
for (var i = list.length; i--; ) {
removed.push.apply(removed, this.add(list[i]));
}
return removed;
};
this.substractPoint = function(pos) {
var i = this.pointIndex(pos);
if (i >= 0)
return this.ranges.splice(i, 1);
};
this.merge = function() {
var removed = [];
var list = this.ranges;
list = list.sort(function(a, b) {
return comparePoints(a.start, b.start);
});
var next = list[0], range;
for (var i = 1; i < list.length; i++) {
range = next;
next = list[i];
var cmp = comparePoints(range.end, next.start);
if (cmp < 0)
continue;
if (cmp == 0 && !range.isEmpty() && !next.isEmpty())
continue;
if (comparePoints(range.end, next.end) < 0) {
range.end.row = next.end.row;
range.end.column = next.end.column;
}
list.splice(i, 1);
removed.push(next);
next = range;
i--;
}
this.ranges = list;
return removed;
};
this.contains = function(row, column) {
return this.pointIndex({row: row, column: column}) >= 0;
};
this.containsPoint = function(pos) {
return this.pointIndex(pos) >= 0;
};
this.rangeAtPoint = function(pos) {
var i = this.pointIndex(pos);
if (i >= 0)
return this.ranges[i];
};
this.clipRows = function(startRow, endRow) {
var list = this.ranges;
if (list[0].start.row > endRow || list[list.length - 1].start.row < startRow)
return [];
var startIndex = this.pointIndex({row: startRow, column: 0});
if (startIndex < 0)
startIndex = -startIndex - 1;
var endIndex = this.pointIndex({row: endRow, column: 0}, startIndex);
if (endIndex < 0)
endIndex = -endIndex - 1;
var clipped = [];
for (var i = startIndex; i < endIndex; i++) {
clipped.push(list[i]);
}
return clipped;
};
this.removeAll = function() {
return this.ranges.splice(0, this.ranges.length);
};
this.attach = function(session) {
if (this.session)
this.detach();
this.session = session;
this.onChange = this.$onChange.bind(this);
this.session.on('change', this.onChange);
};
this.detach = function() {
if (!this.session)
return;
this.session.removeListener('change', this.onChange);
this.session = null;
};
this.$onChange = function(delta) {
if (delta.action == "insert"){
var start = delta.start;
var end = delta.end;
} else {
var end = delta.start;
var start = delta.end;
}
var startRow = start.row;
var endRow = end.row;
var lineDif = endRow - startRow;
var colDiff = -start.column + end.column;
var ranges = this.ranges;
for (var i = 0, n = ranges.length; i < n; i++) {
var r = ranges[i];
if (r.end.row < startRow)
continue;
if (r.start.row > startRow)
break;
if (r.start.row == startRow && r.start.column >= start.column ) {
if (r.start.column == start.column && this.$insertRight) {
} else {
r.start.column += colDiff;
r.start.row += lineDif;
}
}
if (r.end.row == startRow && r.end.column >= start.column) {
if (r.end.column == start.column && this.$insertRight) {
continue;
}
if (r.end.column == start.column && colDiff > 0 && i < n - 1) {
if (r.end.column > r.start.column && r.end.column == ranges[i+1].start.column)
r.end.column -= colDiff;
}
r.end.column += colDiff;
r.end.row += lineDif;
}
}
if (lineDif != 0 && i < n) {
for (; i < n; i++) {
var r = ranges[i];
r.start.row += lineDif;
r.end.row += lineDif;
}
}
};
}).call(RangeList.prototype);
exports.RangeList = RangeList;
});
ace.define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
var RangeList = acequire("../range_list").RangeList;
var oop = acequire("../lib/oop")
var Fold = exports.Fold = function(range, placeholder) {
this.foldLine = null;
this.placeholder = placeholder;
this.range = range;
this.start = range.start;
this.end = range.end;
this.sameRow = range.start.row == range.end.row;
this.subFolds = this.ranges = [];
};
oop.inherits(Fold, RangeList);
(function() {
this.toString = function() {
return '"' + this.placeholder + '" ' + this.range.toString();
};
this.setFoldLine = function(foldLine) {
this.foldLine = foldLine;
this.subFolds.forEach(function(fold) {
fold.setFoldLine(foldLine);
});
};
this.clone = function() {
var range = this.range.clone();
var fold = new Fold(range, this.placeholder);
this.subFolds.forEach(function(subFold) {
fold.subFolds.push(subFold.clone());
});
fold.collapseChildren = this.collapseChildren;
return fold;
};
this.addSubFold = function(fold) {
if (this.range.isEqual(fold))
return;
if (!this.range.containsRange(fold))
throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
consumeRange(fold, this.start);
var row = fold.start.row, column = fold.start.column;
for (var i = 0, cmp = -1; i < this.subFolds.length; i++) {
cmp = this.subFolds[i].range.compare(row, column);
if (cmp != 1)
break;
}
var afterStart = this.subFolds[i];
if (cmp == 0)
return afterStart.addSubFold(fold);
var row = fold.range.end.row, column = fold.range.end.column;
for (var j = i, cmp = -1; j < this.subFolds.length; j++) {
cmp = this.subFolds[j].range.compare(row, column);
if (cmp != 1)
break;
}
var afterEnd = this.subFolds[j];
if (cmp == 0)
throw new Error("A fold can't intersect already existing fold" + fold.range + this.range);
var consumedFolds = this.subFolds.splice(i, j - i, fold);
fold.setFoldLine(this.foldLine);
return fold;
};
this.restoreRange = function(range) {
return restoreRange(range, this.start);
};
}).call(Fold.prototype);
function consumePoint(point, anchor) {
point.row -= anchor.row;
if (point.row == 0)
point.column -= anchor.column;
}
function consumeRange(range, anchor) {
consumePoint(range.start, anchor);
consumePoint(range.end, anchor);
}
function restorePoint(point, anchor) {
if (point.row == 0)
point.column += anchor.column;
point.row += anchor.row;
}
function restoreRange(range, anchor) {
restorePoint(range.start, anchor);
restorePoint(range.end, anchor);
}
});
ace.define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
var FoldLine = acequire("./fold_line").FoldLine;
var Fold = acequire("./fold").Fold;
var TokenIterator = acequire("../token_iterator").TokenIterator;
function Folding() {
this.getFoldAt = function(row, column, side) {
var foldLine = this.getFoldLine(row);
if (!foldLine)
return null;
var folds = foldLine.folds;
for (var i = 0; i < folds.length; i++) {
var fold = folds[i];
if (fold.range.contains(row, column)) {
if (side == 1 && fold.range.isEnd(row, column)) {
continue;
} else if (side == -1 && fold.range.isStart(row, column)) {
continue;
}
return fold;
}
}
};
this.getFoldsInRange = function(range) {
var start = range.start;
var end = range.end;
var foldLines = this.$foldData;
var foundFolds = [];
start.column += 1;
end.column -= 1;
for (var i = 0; i < foldLines.length; i++) {
var cmp = foldLines[i].range.compareRange(range);
if (cmp == 2) {
continue;
}
else if (cmp == -2) {
break;
}
var folds = foldLines[i].folds;
for (var j = 0; j < folds.length; j++) {
var fold = folds[j];
cmp = fold.range.compareRange(range);
if (cmp == -2) {
break;
} else if (cmp == 2) {
continue;
} else
if (cmp == 42) {
break;
}
foundFolds.push(fold);
}
}
start.column -= 1;
end.column += 1;
return foundFolds;
};
this.getFoldsInRangeList = function(ranges) {
if (Array.isArray(ranges)) {
var folds = [];
ranges.forEach(function(range) {
folds = folds.concat(this.getFoldsInRange(range));
}, this);
} else {
var folds = this.getFoldsInRange(ranges);
}
return folds;
};
this.getAllFolds = function() {
var folds = [];
var foldLines = this.$foldData;
for (var i = 0; i < foldLines.length; i++)
for (var j = 0; j < foldLines[i].folds.length; j++)
folds.push(foldLines[i].folds[j]);
return folds;
};
this.getFoldStringAt = function(row, column, trim, foldLine) {
foldLine = foldLine || this.getFoldLine(row);
if (!foldLine)
return null;
var lastFold = {
end: { column: 0 }
};
var str, fold;
for (var i = 0; i < foldLine.folds.length; i++) {
fold = foldLine.folds[i];
var cmp = fold.range.compareEnd(row, column);
if (cmp == -1) {
str = this
.getLine(fold.start.row)
.substring(lastFold.end.column, fold.start.column);
break;
}
else if (cmp === 0) {
return null;
}
lastFold = fold;
}
if (!str)
str = this.getLine(fold.start.row).substring(lastFold.end.column);
if (trim == -1)
return str.substring(0, column - lastFold.end.column);
else if (trim == 1)
return str.substring(column - lastFold.end.column);
else
return str;
};
this.getFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.start.row <= docRow && foldLine.end.row >= docRow) {
return foldLine;
} else if (foldLine.end.row > docRow) {
return null;
}
}
return null;
};
this.getNextFoldLine = function(docRow, startFoldLine) {
var foldData = this.$foldData;
var i = 0;
if (startFoldLine)
i = foldData.indexOf(startFoldLine);
if (i == -1)
i = 0;
for (i; i < foldData.length; i++) {
var foldLine = foldData[i];
if (foldLine.end.row >= docRow) {
return foldLine;
}
}
return null;
};
this.getFoldedRowCount = function(first, last) {
var foldData = this.$foldData, rowCount = last-first+1;
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i],
end = foldLine.end.row,
start = foldLine.start.row;
if (end >= last) {
if (start < last) {
if (start >= first)
rowCount -= last-start;
else
rowCount = 0; // in one fold
}
break;
} else if (end >= first){
if (start >= first) // fold inside range
rowCount -= end-start;
else
rowCount -= end-first+1;
}
}
return rowCount;
};
this.$addFoldLine = function(foldLine) {
this.$foldData.push(foldLine);
this.$foldData.sort(function(a, b) {
return a.start.row - b.start.row;
});
return foldLine;
};
this.addFold = function(placeholder, range) {
var foldData = this.$foldData;
var added = false;
var fold;
if (placeholder instanceof Fold)
fold = placeholder;
else {
fold = new Fold(range, placeholder);
fold.collapseChildren = range.collapseChildren;
}
this.$clipRangeToDocument(fold.range);
var startRow = fold.start.row;
var startColumn = fold.start.column;
var endRow = fold.end.row;
var endColumn = fold.end.column;
if (!(startRow < endRow ||
startRow == endRow && startColumn <= endColumn - 2))
throw new Error("The range has to be at least 2 characters width");
var startFold = this.getFoldAt(startRow, startColumn, 1);
var endFold = this.getFoldAt(endRow, endColumn, -1);
if (startFold && endFold == startFold)
return startFold.addSubFold(fold);
if (startFold && !startFold.range.isStart(startRow, startColumn))
this.removeFold(startFold);
if (endFold && !endFold.range.isEnd(endRow, endColumn))
this.removeFold(endFold);
var folds = this.getFoldsInRange(fold.range);
if (folds.length > 0) {
this.removeFolds(folds);
folds.forEach(function(subFold) {
fold.addSubFold(subFold);
});
}
for (var i = 0; i < foldData.length; i++) {
var foldLine = foldData[i];
if (endRow == foldLine.start.row) {
foldLine.addFold(fold);
added = true;
break;
} else if (startRow == foldLine.end.row) {
foldLine.addFold(fold);
added = true;
if (!fold.sameRow) {
var foldLineNext = foldData[i + 1];
if (foldLineNext && foldLineNext.start.row == endRow) {
foldLine.merge(foldLineNext);
break;
}
}
break;
} else if (endRow <= foldLine.start.row) {
break;
}
}
if (!added)
foldLine = this.$addFoldLine(new FoldLine(this.$foldData, fold));
if (this.$useWrapMode)
this.$updateWrapData(foldLine.start.row, foldLine.start.row);
else
this.$updateRowLengthCache(foldLine.start.row, foldLine.start.row);
this.$modified = true;
this._signal("changeFold", { data: fold, action: "add" });
return fold;
};
this.addFolds = function(folds) {
folds.forEach(function(fold) {
this.addFold(fold);
}, this);
};
this.removeFold = function(fold) {
var foldLine = fold.foldLine;
var startRow = foldLine.start.row;
var endRow = foldLine.end.row;
var foldLines = this.$foldData;
var folds = foldLine.folds;
if (folds.length == 1) {
foldLines.splice(foldLines.indexOf(foldLine), 1);
} else
if (foldLine.range.isEnd(fold.end.row, fold.end.column)) {
folds.pop();
foldLine.end.row = folds[folds.length - 1].end.row;
foldLine.end.column = folds[folds.length - 1].end.column;
} else
if (foldLine.range.isStart(fold.start.row, fold.start.column)) {
folds.shift();
foldLine.start.row = folds[0].start.row;
foldLine.start.column = folds[0].start.column;
} else
if (fold.sameRow) {
folds.splice(folds.indexOf(fold), 1);
} else
{
var newFoldLine = foldLine.split(fold.start.row, fold.start.column);
folds = newFoldLine.folds;
folds.shift();
newFoldLine.start.row = folds[0].start.row;
newFoldLine.start.column = folds[0].start.column;
}
if (!this.$updating) {
if (this.$useWrapMode)
this.$updateWrapData(startRow, endRow);
else
this.$updateRowLengthCache(startRow, endRow);
}
this.$modified = true;
this._signal("changeFold", { data: fold, action: "remove" });
};
this.removeFolds = function(folds) {
var cloneFolds = [];
for (var i = 0; i < folds.length; i++) {
cloneFolds.push(folds[i]);
}
cloneFolds.forEach(function(fold) {
this.removeFold(fold);
}, this);
this.$modified = true;
};
this.expandFold = function(fold) {
this.removeFold(fold);
fold.subFolds.forEach(function(subFold) {
fold.restoreRange(subFold);
this.addFold(subFold);
}, this);
if (fold.collapseChildren > 0) {
this.foldAll(fold.start.row+1, fold.end.row, fold.collapseChildren-1);
}
fold.subFolds = [];
};
this.expandFolds = function(folds) {
folds.forEach(function(fold) {
this.expandFold(fold);
}, this);
};
this.unfold = function(location, expandInner) {
var range, folds;
if (location == null) {
range = new Range(0, 0, this.getLength(), 0);
expandInner = true;
} else if (typeof location == "number")
range = new Range(location, 0, location, this.getLine(location).length);
else if ("row" in location)
range = Range.fromPoints(location, location);
else
range = location;
folds = this.getFoldsInRangeList(range);
if (expandInner) {
this.removeFolds(folds);
} else {
var subFolds = folds;
while (subFolds.length) {
this.expandFolds(subFolds);
subFolds = this.getFoldsInRangeList(range);
}
}
if (folds.length)
return folds;
};
this.isRowFolded = function(docRow, startFoldRow) {
return !!this.getFoldLine(docRow, startFoldRow);
};
this.getRowFoldEnd = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return foldLine ? foldLine.end.row : docRow;
};
this.getRowFoldStart = function(docRow, startFoldRow) {
var foldLine = this.getFoldLine(docRow, startFoldRow);
return foldLine ? foldLine.start.row : docRow;
};
this.getFoldDisplayLine = function(foldLine, endRow, endColumn, startRow, startColumn) {
if (startRow == null)
startRow = foldLine.start.row;
if (startColumn == null)
startColumn = 0;
if (endRow == null)
endRow = foldLine.end.row;
if (endColumn == null)
endColumn = this.getLine(endRow).length;
var doc = this.doc;
var textLine = "";
foldLine.walk(function(placeholder, row, column, lastColumn) {
if (row < startRow)
return;
if (row == startRow) {
if (column < startColumn)
return;
lastColumn = Math.max(startColumn, lastColumn);
}
if (placeholder != null) {
textLine += placeholder;
} else {
textLine += doc.getLine(row).substring(lastColumn, column);
}
}, endRow, endColumn);
return textLine;
};
this.getDisplayLine = function(row, endColumn, startRow, startColumn) {
var foldLine = this.getFoldLine(row);
if (!foldLine) {
var line;
line = this.doc.getLine(row);
return line.substring(startColumn || 0, endColumn || line.length);
} else {
return this.getFoldDisplayLine(
foldLine, row, endColumn, startRow, startColumn);
}
};
this.$cloneFoldData = function() {
var fd = [];
fd = this.$foldData.map(function(foldLine) {
var folds = foldLine.folds.map(function(fold) {
return fold.clone();
});
return new FoldLine(fd, folds);
});
return fd;
};
this.toggleFold = function(tryToUnfold) {
var selection = this.selection;
var range = selection.getRange();
var fold;
var bracketPos;
if (range.isEmpty()) {
var cursor = range.start;
fold = this.getFoldAt(cursor.row, cursor.column);
if (fold) {
this.expandFold(fold);
return;
} else if (bracketPos = this.findMatchingBracket(cursor)) {
if (range.comparePoint(bracketPos) == 1) {
range.end = bracketPos;
} else {
range.start = bracketPos;
range.start.column++;
range.end.column--;
}
} else if (bracketPos = this.findMatchingBracket({row: cursor.row, column: cursor.column + 1})) {
if (range.comparePoint(bracketPos) == 1)
range.end = bracketPos;
else
range.start = bracketPos;
range.start.column++;
} else {
range = this.getCommentFoldRange(cursor.row, cursor.column) || range;
}
} else {
var folds = this.getFoldsInRange(range);
if (tryToUnfold && folds.length) {
this.expandFolds(folds);
return;
} else if (folds.length == 1 ) {
fold = folds[0];
}
}
if (!fold)
fold = this.getFoldAt(range.start.row, range.start.column);
if (fold && fold.range.toString() == range.toString()) {
this.expandFold(fold);
return;
}
var placeholder = "...";
if (!range.isMultiLine()) {
placeholder = this.getTextRange(range);
if (placeholder.length < 4)
return;
placeholder = placeholder.trim().substring(0, 2) + "..";
}
this.addFold(placeholder, range);
};
this.getCommentFoldRange = function(row, column, dir) {
var iterator = new TokenIterator(this, row, column);
var token = iterator.getCurrentToken();
if (token && /^comment|string/.test(token.type)) {
var range = new Range();
var re = new RegExp(token.type.replace(/\..*/, "\\."));
if (dir != 1) {
do {
token = iterator.stepBackward();
} while (token && re.test(token.type));
iterator.stepForward();
}
range.start.row = iterator.getCurrentTokenRow();
range.start.column = iterator.getCurrentTokenColumn() + 2;
iterator = new TokenIterator(this, row, column);
if (dir != -1) {
do {
token = iterator.stepForward();
} while (token && re.test(token.type));
token = iterator.stepBackward();
} else
token = iterator.getCurrentToken();
range.end.row = iterator.getCurrentTokenRow();
range.end.column = iterator.getCurrentTokenColumn() + token.value.length - 2;
return range;
}
};
this.foldAll = function(startRow, endRow, depth) {
if (depth == undefined)
depth = 100000; // JSON.stringify doesn't hanle Infinity
var foldWidgets = this.foldWidgets;
if (!foldWidgets)
return; // mode doesn't support folding
endRow = endRow || this.getLength();
startRow = startRow || 0;
for (var row = startRow; row < endRow; row++) {
if (foldWidgets[row] == null)
foldWidgets[row] = this.getFoldWidget(row);
if (foldWidgets[row] != "start")
continue;
var range = this.getFoldWidgetRange(row);
if (range && range.isMultiLine()
&& range.end.row <= endRow
&& range.start.row >= startRow
) {
row = range.end.row;
try {
var fold = this.addFold("...", range);
if (fold)
fold.collapseChildren = depth;
} catch(e) {}
}
}
};
this.$foldStyles = {
"manual": 1,
"markbegin": 1,
"markbeginend": 1
};
this.$foldStyle = "markbegin";
this.setFoldStyle = function(style) {
if (!this.$foldStyles[style])
throw new Error("invalid fold style: " + style + "[" + Object.keys(this.$foldStyles).join(", ") + "]");
if (this.$foldStyle == style)
return;
this.$foldStyle = style;
if (style == "manual")
this.unfold();
var mode = this.$foldMode;
this.$setFolding(null);
this.$setFolding(mode);
};
this.$setFolding = function(foldMode) {
if (this.$foldMode == foldMode)
return;
this.$foldMode = foldMode;
this.off('change', this.$updateFoldWidgets);
this.off('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
this._signal("changeAnnotation");
if (!foldMode || this.$foldStyle == "manual") {
this.foldWidgets = null;
return;
}
this.foldWidgets = [];
this.getFoldWidget = foldMode.getFoldWidget.bind(foldMode, this, this.$foldStyle);
this.getFoldWidgetRange = foldMode.getFoldWidgetRange.bind(foldMode, this, this.$foldStyle);
this.$updateFoldWidgets = this.updateFoldWidgets.bind(this);
this.$tokenizerUpdateFoldWidgets = this.tokenizerUpdateFoldWidgets.bind(this);
this.on('change', this.$updateFoldWidgets);
this.on('tokenizerUpdate', this.$tokenizerUpdateFoldWidgets);
};
this.getParentFoldRangeData = function (row, ignoreCurrent) {
var fw = this.foldWidgets;
if (!fw || (ignoreCurrent && fw[row]))
return {};
var i = row - 1, firstRange;
while (i >= 0) {
var c = fw[i];
if (c == null)
c = fw[i] = this.getFoldWidget(i);
if (c == "start") {
var range = this.getFoldWidgetRange(i);
if (!firstRange)
firstRange = range;
if (range && range.end.row >= row)
break;
}
i--;
}
return {
range: i !== -1 && range,
firstRange: firstRange
};
};
this.onFoldWidgetClick = function(row, e) {
e = e.domEvent;
var options = {
children: e.shiftKey,
all: e.ctrlKey || e.metaKey,
siblings: e.altKey
};
var range = this.$toggleFoldWidget(row, options);
if (!range) {
var el = (e.target || e.srcElement);
if (el && /ace_fold-widget/.test(el.className))
el.className += " ace_invalid";
}
};
this.$toggleFoldWidget = function(row, options) {
if (!this.getFoldWidget)
return;
var type = this.getFoldWidget(row);
var line = this.getLine(row);
var dir = type === "end" ? -1 : 1;
var fold = this.getFoldAt(row, dir === -1 ? 0 : line.length, dir);
if (fold) {
if (options.children || options.all)
this.removeFold(fold);
else
this.expandFold(fold);
return fold;
}
var range = this.getFoldWidgetRange(row, true);
if (range && !range.isMultiLine()) {
fold = this.getFoldAt(range.start.row, range.start.column, 1);
if (fold && range.isEqual(fold.range)) {
this.removeFold(fold);
return fold;
}
}
if (options.siblings) {
var data = this.getParentFoldRangeData(row);
if (data.range) {
var startRow = data.range.start.row + 1;
var endRow = data.range.end.row;
}
this.foldAll(startRow, endRow, options.all ? 10000 : 0);
} else if (options.children) {
endRow = range ? range.end.row : this.getLength();
this.foldAll(row + 1, endRow, options.all ? 10000 : 0);
} else if (range) {
if (options.all)
range.collapseChildren = 10000;
this.addFold("...", range);
}
return range;
};
this.toggleFoldWidget = function(toggleParent) {
var row = this.selection.getCursor().row;
row = this.getRowFoldStart(row);
var range = this.$toggleFoldWidget(row, {});
if (range)
return;
var data = this.getParentFoldRangeData(row, true);
range = data.range || data.firstRange;
if (range) {
row = range.start.row;
var fold = this.getFoldAt(row, this.getLine(row).length, 1);
if (fold) {
this.removeFold(fold);
} else {
this.addFold("...", range);
}
}
};
this.updateFoldWidgets = function(delta) {
var firstRow = delta.start.row;
var len = delta.end.row - firstRow;
if (len === 0) {
this.foldWidgets[firstRow] = null;
} else if (delta.action == 'remove') {
this.foldWidgets.splice(firstRow, len + 1, null);
} else {
var args = Array(len + 1);
args.unshift(firstRow, 1);
this.foldWidgets.splice.apply(this.foldWidgets, args);
}
};
this.tokenizerUpdateFoldWidgets = function(e) {
var rows = e.data;
if (rows.first != rows.last) {
if (this.foldWidgets.length > rows.first)
this.foldWidgets.splice(rows.first, this.foldWidgets.length);
}
};
}
exports.Folding = Folding;
});
ace.define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"], function(acequire, exports, module) {
"use strict";
var TokenIterator = acequire("../token_iterator").TokenIterator;
var Range = acequire("../range").Range;
function BracketMatch() {
this.findMatchingBracket = function(position, chr) {
if (position.column == 0) return null;
var charBeforeCursor = chr || this.getLine(position.row).charAt(position.column-1);
if (charBeforeCursor == "") return null;
var match = charBeforeCursor.match(/([\(\[\{])|([\)\]\}])/);
if (!match)
return null;
if (match[1])
return this.$findClosingBracket(match[1], position);
else
return this.$findOpeningBracket(match[2], position);
};
this.getBracketRange = function(pos) {
var line = this.getLine(pos.row);
var before = true, range;
var chr = line.charAt(pos.column-1);
var match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
if (!match) {
chr = line.charAt(pos.column);
pos = {row: pos.row, column: pos.column + 1};
match = chr && chr.match(/([\(\[\{])|([\)\]\}])/);
before = false;
}
if (!match)
return null;
if (match[1]) {
var bracketPos = this.$findClosingBracket(match[1], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(pos, bracketPos);
if (!before) {
range.end.column++;
range.start.column--;
}
range.cursor = range.end;
} else {
var bracketPos = this.$findOpeningBracket(match[2], pos);
if (!bracketPos)
return null;
range = Range.fromPoints(bracketPos, pos);
if (!before) {
range.start.column++;
range.end.column--;
}
range.cursor = range.start;
}
return range;
};
this.$brackets = {
")": "(",
"(": ")",
"]": "[",
"[": "]",
"{": "}",
"}": "{"
};
this.$findOpeningBracket = function(bracket, position, typeRe) {
var openBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("rparen", ".paren")
.replace(/\b(?:end)\b/, "(?:start|begin|end)")
+ ")+"
);
}
var valueIndex = position.column - iterator.getCurrentTokenColumn() - 2;
var value = token.value;
while (true) {
while (valueIndex >= 0) {
var chr = value.charAt(valueIndex);
if (chr == openBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex -= 1;
}
do {
token = iterator.stepBackward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
value = token.value;
valueIndex = value.length - 1;
}
return null;
};
this.$findClosingBracket = function(bracket, position, typeRe) {
var closingBracket = this.$brackets[bracket];
var depth = 1;
var iterator = new TokenIterator(this, position.row, position.column);
var token = iterator.getCurrentToken();
if (!token)
token = iterator.stepForward();
if (!token)
return;
if (!typeRe){
typeRe = new RegExp(
"(\\.?" +
token.type.replace(".", "\\.").replace("lparen", ".paren")
.replace(/\b(?:start|begin)\b/, "(?:start|begin|end)")
+ ")+"
);
}
var valueIndex = position.column - iterator.getCurrentTokenColumn();
while (true) {
var value = token.value;
var valueLength = value.length;
while (valueIndex < valueLength) {
var chr = value.charAt(valueIndex);
if (chr == closingBracket) {
depth -= 1;
if (depth == 0) {
return {row: iterator.getCurrentTokenRow(),
column: valueIndex + iterator.getCurrentTokenColumn()};
}
}
else if (chr == bracket) {
depth += 1;
}
valueIndex += 1;
}
do {
token = iterator.stepForward();
} while (token && !typeRe.test(token.type));
if (token == null)
break;
valueIndex = 0;
}
return null;
};
}
exports.BracketMatch = BracketMatch;
});
ace.define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var lang = acequire("./lib/lang");
var config = acequire("./config");
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var Selection = acequire("./selection").Selection;
var TextMode = acequire("./mode/text").Mode;
var Range = acequire("./range").Range;
var Document = acequire("./document").Document;
var BackgroundTokenizer = acequire("./background_tokenizer").BackgroundTokenizer;
var SearchHighlight = acequire("./search_highlight").SearchHighlight;
var EditSession = function(text, mode) {
this.$breakpoints = [];
this.$decorations = [];
this.$frontMarkers = {};
this.$backMarkers = {};
this.$markerId = 1;
this.$undoSelect = true;
this.$foldData = [];
this.id = "session" + (++EditSession.$uid);
this.$foldData.toString = function() {
return this.join("\n");
};
this.on("changeFold", this.onChangeFold.bind(this));
this.$onChange = this.onChange.bind(this);
if (typeof text != "object" || !text.getLine)
text = new Document(text);
this.setDocument(text);
this.selection = new Selection(this);
config.resetOptions(this);
this.setMode(mode);
config._signal("session", this);
};
(function() {
oop.implement(this, EventEmitter);
this.setDocument = function(doc) {
if (this.doc)
this.doc.removeListener("change", this.$onChange);
this.doc = doc;
doc.on("change", this.$onChange);
if (this.bgTokenizer)
this.bgTokenizer.setDocument(this.getDocument());
this.resetCaches();
};
this.getDocument = function() {
return this.doc;
};
this.$resetRowCache = function(docRow) {
if (!docRow) {
this.$docRowCache = [];
this.$screenRowCache = [];
return;
}
var l = this.$docRowCache.length;
var i = this.$getRowCacheIndex(this.$docRowCache, docRow) + 1;
if (l > i) {
this.$docRowCache.splice(i, l);
this.$screenRowCache.splice(i, l);
}
};
this.$getRowCacheIndex = function(cacheArray, val) {
var low = 0;
var hi = cacheArray.length - 1;
while (low <= hi) {
var mid = (low + hi) >> 1;
var c = cacheArray[mid];
if (val > c)
low = mid + 1;
else if (val < c)
hi = mid - 1;
else
return mid;
}
return low -1;
};
this.resetCaches = function() {
this.$modified = true;
this.$wrapData = [];
this.$rowLengthCache = [];
this.$resetRowCache(0);
if (this.bgTokenizer)
this.bgTokenizer.start(0);
};
this.onChangeFold = function(e) {
var fold = e.data;
this.$resetRowCache(fold.start.row);
};
this.onChange = function(delta) {
this.$modified = true;
this.$resetRowCache(delta.start.row);
var removedFolds = this.$updateInternalDataOnChange(delta);
if (!this.$fromUndo && this.$undoManager && !delta.ignore) {
this.$deltasDoc.push(delta);
if (removedFolds && removedFolds.length != 0) {
this.$deltasFold.push({
action: "removeFolds",
folds: removedFolds
});
}
this.$informUndoManager.schedule();
}
this.bgTokenizer && this.bgTokenizer.$updateOnChange(delta);
this._signal("change", delta);
};
this.setValue = function(text) {
this.doc.setValue(text);
this.selection.moveTo(0, 0);
this.$resetRowCache(0);
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
this.setUndoManager(this.$undoManager);
this.getUndoManager().reset();
};
this.getValue =
this.toString = function() {
return this.doc.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.getState = function(row) {
return this.bgTokenizer.getState(row);
};
this.getTokens = function(row) {
return this.bgTokenizer.getTokens(row);
};
this.getTokenAt = function(row, column) {
var tokens = this.bgTokenizer.getTokens(row);
var token, c = 0;
if (column == null) {
i = tokens.length - 1;
c = this.getLine(row).length;
} else {
for (var i = 0; i < tokens.length; i++) {
c += tokens[i].value.length;
if (c >= column)
break;
}
}
token = tokens[i];
if (!token)
return null;
token.index = i;
token.start = c - token.value.length;
return token;
};
this.setUndoManager = function(undoManager) {
this.$undoManager = undoManager;
this.$deltas = [];
this.$deltasDoc = [];
this.$deltasFold = [];
if (this.$informUndoManager)
this.$informUndoManager.cancel();
if (undoManager) {
var self = this;
this.$syncInformUndoManager = function() {
self.$informUndoManager.cancel();
if (self.$deltasFold.length) {
self.$deltas.push({
group: "fold",
deltas: self.$deltasFold
});
self.$deltasFold = [];
}
if (self.$deltasDoc.length) {
self.$deltas.push({
group: "doc",
deltas: self.$deltasDoc
});
self.$deltasDoc = [];
}
if (self.$deltas.length > 0) {
undoManager.execute({
action: "aceupdate",
args: [self.$deltas, self],
merge: self.mergeUndoDeltas
});
}
self.mergeUndoDeltas = false;
self.$deltas = [];
};
this.$informUndoManager = lang.delayedCall(this.$syncInformUndoManager);
}
};
this.markUndoGroup = function() {
if (this.$syncInformUndoManager)
this.$syncInformUndoManager();
};
this.$defaultUndoManager = {
undo: function() {},
redo: function() {},
reset: function() {}
};
this.getUndoManager = function() {
return this.$undoManager || this.$defaultUndoManager;
};
this.getTabString = function() {
if (this.getUseSoftTabs()) {
return lang.stringRepeat(" ", this.getTabSize());
} else {
return "\t";
}
};
this.setUseSoftTabs = function(val) {
this.setOption("useSoftTabs", val);
};
this.getUseSoftTabs = function() {
return this.$useSoftTabs && !this.$mode.$indentWithTabs;
};
this.setTabSize = function(tabSize) {
this.setOption("tabSize", tabSize);
};
this.getTabSize = function() {
return this.$tabSize;
};
this.isTabStop = function(position) {
return this.$useSoftTabs && (position.column % this.$tabSize === 0);
};
this.$overwrite = false;
this.setOverwrite = function(overwrite) {
this.setOption("overwrite", overwrite);
};
this.getOverwrite = function() {
return this.$overwrite;
};
this.toggleOverwrite = function() {
this.setOverwrite(!this.$overwrite);
};
this.addGutterDecoration = function(row, className) {
if (!this.$decorations[row])
this.$decorations[row] = "";
this.$decorations[row] += " " + className;
this._signal("changeBreakpoint", {});
};
this.removeGutterDecoration = function(row, className) {
this.$decorations[row] = (this.$decorations[row] || "").replace(" " + className, "");
this._signal("changeBreakpoint", {});
};
this.getBreakpoints = function() {
return this.$breakpoints;
};
this.setBreakpoints = function(rows) {
this.$breakpoints = [];
for (var i=0; i<rows.length; i++) {
this.$breakpoints[rows[i]] = "ace_breakpoint";
}
this._signal("changeBreakpoint", {});
};
this.clearBreakpoints = function() {
this.$breakpoints = [];
this._signal("changeBreakpoint", {});
};
this.setBreakpoint = function(row, className) {
if (className === undefined)
className = "ace_breakpoint";
if (className)
this.$breakpoints[row] = className;
else
delete this.$breakpoints[row];
this._signal("changeBreakpoint", {});
};
this.clearBreakpoint = function(row) {
delete this.$breakpoints[row];
this._signal("changeBreakpoint", {});
};
this.addMarker = function(range, clazz, type, inFront) {
var id = this.$markerId++;
var marker = {
range : range,
type : type || "line",
renderer: typeof type == "function" ? type : null,
clazz : clazz,
inFront: !!inFront,
id: id
};
if (inFront) {
this.$frontMarkers[id] = marker;
this._signal("changeFrontMarker");
} else {
this.$backMarkers[id] = marker;
this._signal("changeBackMarker");
}
return id;
};
this.addDynamicMarker = function(marker, inFront) {
if (!marker.update)
return;
var id = this.$markerId++;
marker.id = id;
marker.inFront = !!inFront;
if (inFront) {
this.$frontMarkers[id] = marker;
this._signal("changeFrontMarker");
} else {
this.$backMarkers[id] = marker;
this._signal("changeBackMarker");
}
return marker;
};
this.removeMarker = function(markerId) {
var marker = this.$frontMarkers[markerId] || this.$backMarkers[markerId];
if (!marker)
return;
var markers = marker.inFront ? this.$frontMarkers : this.$backMarkers;
if (marker) {
delete (markers[markerId]);
this._signal(marker.inFront ? "changeFrontMarker" : "changeBackMarker");
}
};
this.getMarkers = function(inFront) {
return inFront ? this.$frontMarkers : this.$backMarkers;
};
this.highlight = function(re) {
if (!this.$searchHighlight) {
var highlight = new SearchHighlight(null, "ace_selected-word", "text");
this.$searchHighlight = this.addDynamicMarker(highlight);
}
this.$searchHighlight.setRegexp(re);
};
this.highlightLines = function(startRow, endRow, clazz, inFront) {
if (typeof endRow != "number") {
clazz = endRow;
endRow = startRow;
}
if (!clazz)
clazz = "ace_step";
var range = new Range(startRow, 0, endRow, Infinity);
range.id = this.addMarker(range, clazz, "fullLine", inFront);
return range;
};
this.setAnnotations = function(annotations) {
this.$annotations = annotations;
this._signal("changeAnnotation", {});
};
this.getAnnotations = function() {
return this.$annotations || [];
};
this.clearAnnotations = function() {
this.setAnnotations([]);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r?\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getWordRange = function(row, column) {
var line = this.getLine(row);
var inToken = false;
if (column > 0)
inToken = !!line.charAt(column - 1).match(this.tokenRe);
if (!inToken)
inToken = !!line.charAt(column).match(this.tokenRe);
if (inToken)
var re = this.tokenRe;
else if (/^\s+$/.test(line.slice(column-1, column+1)))
var re = /\s/;
else
var re = this.nonTokenRe;
var start = column;
if (start > 0) {
do {
start--;
}
while (start >= 0 && line.charAt(start).match(re));
start++;
}
var end = column;
while (end < line.length && line.charAt(end).match(re)) {
end++;
}
return new Range(row, start, row, end);
};
this.getAWordRange = function(row, column) {
var wordRange = this.getWordRange(row, column);
var line = this.getLine(wordRange.end.row);
while (line.charAt(wordRange.end.column).match(/[ \t]/)) {
wordRange.end.column += 1;
}
return wordRange;
};
this.setNewLineMode = function(newLineMode) {
this.doc.setNewLineMode(newLineMode);
};
this.getNewLineMode = function() {
return this.doc.getNewLineMode();
};
this.setUseWorker = function(useWorker) { this.setOption("useWorker", useWorker); };
this.getUseWorker = function() { return this.$useWorker; };
this.onReloadTokenizer = function(e) {
var rows = e.data;
this.bgTokenizer.start(rows.first);
this._signal("tokenizerUpdate", e);
};
this.$modes = {};
this.$mode = null;
this.$modeId = null;
this.setMode = function(mode, cb) {
if (mode && typeof mode === "object") {
if (mode.getTokenizer)
return this.$onChangeMode(mode);
var options = mode;
var path = options.path;
} else {
path = mode || "ace/mode/text";
}
if (!this.$modes["ace/mode/text"])
this.$modes["ace/mode/text"] = new TextMode();
if (this.$modes[path] && !options) {
this.$onChangeMode(this.$modes[path]);
cb && cb();
return;
}
this.$modeId = path;
config.loadModule(["mode", path], function(m) {
if (this.$modeId !== path)
return cb && cb();
if (this.$modes[path] && !options) {
this.$onChangeMode(this.$modes[path]);
} else if (m && m.Mode) {
m = new m.Mode(options);
if (!options) {
this.$modes[path] = m;
m.$id = path;
}
this.$onChangeMode(m);
}
cb && cb();
}.bind(this));
if (!this.$mode)
this.$onChangeMode(this.$modes["ace/mode/text"], true);
};
this.$onChangeMode = function(mode, $isPlaceholder) {
if (!$isPlaceholder)
this.$modeId = mode.$id;
if (this.$mode === mode)
return;
this.$mode = mode;
this.$stopWorker();
if (this.$useWorker)
this.$startWorker();
var tokenizer = mode.getTokenizer();
if(tokenizer.addEventListener !== undefined) {
var onReloadTokenizer = this.onReloadTokenizer.bind(this);
tokenizer.addEventListener("update", onReloadTokenizer);
}
if (!this.bgTokenizer) {
this.bgTokenizer = new BackgroundTokenizer(tokenizer);
var _self = this;
this.bgTokenizer.addEventListener("update", function(e) {
_self._signal("tokenizerUpdate", e);
});
} else {
this.bgTokenizer.setTokenizer(tokenizer);
}
this.bgTokenizer.setDocument(this.getDocument());
this.tokenRe = mode.tokenRe;
this.nonTokenRe = mode.nonTokenRe;
if (!$isPlaceholder) {
if (mode.attachToSession)
mode.attachToSession(this);
this.$options.wrapMethod.set.call(this, this.$wrapMethod);
this.$setFolding(mode.foldingRules);
this.bgTokenizer.start(0);
this._emit("changeMode");
}
};
this.$stopWorker = function() {
if (this.$worker) {
this.$worker.terminate();
this.$worker = null;
}
};
this.$startWorker = function() {
try {
this.$worker = this.$mode.createWorker(this);
} catch (e) {
config.warn("Could not load worker", e);
this.$worker = null;
}
};
this.getMode = function() {
return this.$mode;
};
this.$scrollTop = 0;
this.setScrollTop = function(scrollTop) {
if (this.$scrollTop === scrollTop || isNaN(scrollTop))
return;
this.$scrollTop = scrollTop;
this._signal("changeScrollTop", scrollTop);
};
this.getScrollTop = function() {
return this.$scrollTop;
};
this.$scrollLeft = 0;
this.setScrollLeft = function(scrollLeft) {
if (this.$scrollLeft === scrollLeft || isNaN(scrollLeft))
return;
this.$scrollLeft = scrollLeft;
this._signal("changeScrollLeft", scrollLeft);
};
this.getScrollLeft = function() {
return this.$scrollLeft;
};
this.getScreenWidth = function() {
this.$computeWidth();
if (this.lineWidgets)
return Math.max(this.getLineWidgetMaxWidth(), this.screenWidth);
return this.screenWidth;
};
this.getLineWidgetMaxWidth = function() {
if (this.lineWidgetsWidth != null) return this.lineWidgetsWidth;
var width = 0;
this.lineWidgets.forEach(function(w) {
if (w && w.screenWidth > width)
width = w.screenWidth;
});
return this.lineWidgetWidth = width;
};
this.$computeWidth = function(force) {
if (this.$modified || force) {
this.$modified = false;
if (this.$useWrapMode)
return this.screenWidth = this.$wrapLimit;
var lines = this.doc.getAllLines();
var cache = this.$rowLengthCache;
var longestScreenLine = 0;
var foldIndex = 0;
var foldLine = this.$foldData[foldIndex];
var foldStart = foldLine ? foldLine.start.row : Infinity;
var len = lines.length;
for (var i = 0; i < len; i++) {
if (i > foldStart) {
i = foldLine.end.row + 1;
if (i >= len)
break;
foldLine = this.$foldData[foldIndex++];
foldStart = foldLine ? foldLine.start.row : Infinity;
}
if (cache[i] == null)
cache[i] = this.$getStringScreenWidth(lines[i])[0];
if (cache[i] > longestScreenLine)
longestScreenLine = cache[i];
}
this.screenWidth = longestScreenLine;
}
};
this.getLine = function(row) {
return this.doc.getLine(row);
};
this.getLines = function(firstRow, lastRow) {
return this.doc.getLines(firstRow, lastRow);
};
this.getLength = function() {
return this.doc.getLength();
};
this.getTextRange = function(range) {
return this.doc.getTextRange(range || this.selection.getRange());
};
this.insert = function(position, text) {
return this.doc.insert(position, text);
};
this.remove = function(range) {
return this.doc.remove(range);
};
this.removeFullLines = function(firstRow, lastRow){
return this.doc.removeFullLines(firstRow, lastRow);
};
this.undoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = deltas.length - 1; i != -1; i--) {
var delta = deltas[i];
if (delta.group == "doc") {
this.doc.revertDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, true, lastUndoRange);
} else {
delta.deltas.forEach(function(foldDelta) {
this.addFolds(foldDelta.folds);
}, this);
}
}
this.$fromUndo = false;
lastUndoRange &&
this.$undoSelect &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
};
this.redoChanges = function(deltas, dontSelect) {
if (!deltas.length)
return;
this.$fromUndo = true;
var lastUndoRange = null;
for (var i = 0; i < deltas.length; i++) {
var delta = deltas[i];
if (delta.group == "doc") {
this.doc.applyDeltas(delta.deltas);
lastUndoRange =
this.$getUndoSelection(delta.deltas, false, lastUndoRange);
}
}
this.$fromUndo = false;
lastUndoRange &&
this.$undoSelect &&
!dontSelect &&
this.selection.setSelectionRange(lastUndoRange);
return lastUndoRange;
};
this.setUndoSelect = function(enable) {
this.$undoSelect = enable;
};
this.$getUndoSelection = function(deltas, isUndo, lastUndoRange) {
function isInsert(delta) {
return isUndo ? delta.action !== "insert" : delta.action === "insert";
}
var delta = deltas[0];
var range, point;
var lastDeltaIsInsert = false;
if (isInsert(delta)) {
range = Range.fromPoints(delta.start, delta.end);
lastDeltaIsInsert = true;
} else {
range = Range.fromPoints(delta.start, delta.start);
lastDeltaIsInsert = false;
}
for (var i = 1; i < deltas.length; i++) {
delta = deltas[i];
if (isInsert(delta)) {
point = delta.start;
if (range.compare(point.row, point.column) == -1) {
range.setStart(point);
}
point = delta.end;
if (range.compare(point.row, point.column) == 1) {
range.setEnd(point);
}
lastDeltaIsInsert = true;
} else {
point = delta.start;
if (range.compare(point.row, point.column) == -1) {
range = Range.fromPoints(delta.start, delta.start);
}
lastDeltaIsInsert = false;
}
}
if (lastUndoRange != null) {
if (Range.comparePoints(lastUndoRange.start, range.start) === 0) {
lastUndoRange.start.column += range.end.column - range.start.column;
lastUndoRange.end.column += range.end.column - range.start.column;
}
var cmp = lastUndoRange.compareRange(range);
if (cmp == 1) {
range.setStart(lastUndoRange.start);
} else if (cmp == -1) {
range.setEnd(lastUndoRange.end);
}
}
return range;
};
this.replace = function(range, text) {
return this.doc.replace(range, text);
};
this.moveText = function(fromRange, toPosition, copy) {
var text = this.getTextRange(fromRange);
var folds = this.getFoldsInRange(fromRange);
var toRange = Range.fromPoints(toPosition, toPosition);
if (!copy) {
this.remove(fromRange);
var rowDiff = fromRange.start.row - fromRange.end.row;
var collDiff = rowDiff ? -fromRange.end.column : fromRange.start.column - fromRange.end.column;
if (collDiff) {
if (toRange.start.row == fromRange.end.row && toRange.start.column > fromRange.end.column)
toRange.start.column += collDiff;
if (toRange.end.row == fromRange.end.row && toRange.end.column > fromRange.end.column)
toRange.end.column += collDiff;
}
if (rowDiff && toRange.start.row >= fromRange.end.row) {
toRange.start.row += rowDiff;
toRange.end.row += rowDiff;
}
}
toRange.end = this.insert(toRange.start, text);
if (folds.length) {
var oldStart = fromRange.start;
var newStart = toRange.start;
var rowDiff = newStart.row - oldStart.row;
var collDiff = newStart.column - oldStart.column;
this.addFolds(folds.map(function(x) {
x = x.clone();
if (x.start.row == oldStart.row)
x.start.column += collDiff;
if (x.end.row == oldStart.row)
x.end.column += collDiff;
x.start.row += rowDiff;
x.end.row += rowDiff;
return x;
}));
}
return toRange;
};
this.indentRows = function(startRow, endRow, indentString) {
indentString = indentString.replace(/\t/g, this.getTabString());
for (var row=startRow; row<=endRow; row++)
this.doc.insertInLine({row: row, column: 0}, indentString);
};
this.outdentRows = function (range) {
var rowRange = range.collapseRows();
var deleteRange = new Range(0, 0, 0, 0);
var size = this.getTabSize();
for (var i = rowRange.start.row; i <= rowRange.end.row; ++i) {
var line = this.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
for (var j = 0; j < size; ++j)
if (line.charAt(j) != ' ')
break;
if (j < size && line.charAt(j) == '\t') {
deleteRange.start.column = j;
deleteRange.end.column = j + 1;
} else {
deleteRange.start.column = 0;
deleteRange.end.column = j;
}
this.remove(deleteRange);
}
};
this.$moveLines = function(firstRow, lastRow, dir) {
firstRow = this.getRowFoldStart(firstRow);
lastRow = this.getRowFoldEnd(lastRow);
if (dir < 0) {
var row = this.getRowFoldStart(firstRow + dir);
if (row < 0) return 0;
var diff = row-firstRow;
} else if (dir > 0) {
var row = this.getRowFoldEnd(lastRow + dir);
if (row > this.doc.getLength()-1) return 0;
var diff = row-lastRow;
} else {
firstRow = this.$clipRowToDocument(firstRow);
lastRow = this.$clipRowToDocument(lastRow);
var diff = lastRow - firstRow + 1;
}
var range = new Range(firstRow, 0, lastRow, Number.MAX_VALUE);
var folds = this.getFoldsInRange(range).map(function(x){
x = x.clone();
x.start.row += diff;
x.end.row += diff;
return x;
});
var lines = dir == 0
? this.doc.getLines(firstRow, lastRow)
: this.doc.removeFullLines(firstRow, lastRow);
this.doc.insertFullLines(firstRow+diff, lines);
folds.length && this.addFolds(folds);
return diff;
};
this.moveLinesUp = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, -1);
};
this.moveLinesDown = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, 1);
};
this.duplicateLines = function(firstRow, lastRow) {
return this.$moveLines(firstRow, lastRow, 0);
};
this.$clipRowToDocument = function(row) {
return Math.max(0, Math.min(row, this.doc.getLength()-1));
};
this.$clipColumnToRow = function(row, column) {
if (column < 0)
return 0;
return Math.min(this.doc.getLine(row).length, column);
};
this.$clipPositionToDocument = function(row, column) {
column = Math.max(0, column);
if (row < 0) {
row = 0;
column = 0;
} else {
var len = this.doc.getLength();
if (row >= len) {
row = len - 1;
column = this.doc.getLine(len-1).length;
} else {
column = Math.min(this.doc.getLine(row).length, column);
}
}
return {
row: row,
column: column
};
};
this.$clipRangeToDocument = function(range) {
if (range.start.row < 0) {
range.start.row = 0;
range.start.column = 0;
} else {
range.start.column = this.$clipColumnToRow(
range.start.row,
range.start.column
);
}
var len = this.doc.getLength() - 1;
if (range.end.row > len) {
range.end.row = len;
range.end.column = this.doc.getLine(len).length;
} else {
range.end.column = this.$clipColumnToRow(
range.end.row,
range.end.column
);
}
return range;
};
this.$wrapLimit = 80;
this.$useWrapMode = false;
this.$wrapLimitRange = {
min : null,
max : null
};
this.setUseWrapMode = function(useWrapMode) {
if (useWrapMode != this.$useWrapMode) {
this.$useWrapMode = useWrapMode;
this.$modified = true;
this.$resetRowCache(0);
if (useWrapMode) {
var len = this.getLength();
this.$wrapData = Array(len);
this.$updateWrapData(0, len - 1);
}
this._signal("changeWrapMode");
}
};
this.getUseWrapMode = function() {
return this.$useWrapMode;
};
this.setWrapLimitRange = function(min, max) {
if (this.$wrapLimitRange.min !== min || this.$wrapLimitRange.max !== max) {
this.$wrapLimitRange = { min: min, max: max };
this.$modified = true;
if (this.$useWrapMode)
this._signal("changeWrapMode");
}
};
this.adjustWrapLimit = function(desiredLimit, $printMargin) {
var limits = this.$wrapLimitRange;
if (limits.max < 0)
limits = {min: $printMargin, max: $printMargin};
var wrapLimit = this.$constrainWrapLimit(desiredLimit, limits.min, limits.max);
if (wrapLimit != this.$wrapLimit && wrapLimit > 1) {
this.$wrapLimit = wrapLimit;
this.$modified = true;
if (this.$useWrapMode) {
this.$updateWrapData(0, this.getLength() - 1);
this.$resetRowCache(0);
this._signal("changeWrapLimit");
}
return true;
}
return false;
};
this.$constrainWrapLimit = function(wrapLimit, min, max) {
if (min)
wrapLimit = Math.max(min, wrapLimit);
if (max)
wrapLimit = Math.min(max, wrapLimit);
return wrapLimit;
};
this.getWrapLimit = function() {
return this.$wrapLimit;
};
this.setWrapLimit = function (limit) {
this.setWrapLimitRange(limit, limit);
};
this.getWrapLimitRange = function() {
return {
min : this.$wrapLimitRange.min,
max : this.$wrapLimitRange.max
};
};
this.$updateInternalDataOnChange = function(delta) {
var useWrapMode = this.$useWrapMode;
var action = delta.action;
var start = delta.start;
var end = delta.end;
var firstRow = start.row;
var lastRow = end.row;
var len = lastRow - firstRow;
var removedFolds = null;
this.$updating = true;
if (len != 0) {
if (action === "remove") {
this[useWrapMode ? "$wrapData" : "$rowLengthCache"].splice(firstRow, len);
var foldLines = this.$foldData;
removedFolds = this.getFoldsInRange(delta);
this.removeFolds(removedFolds);
var foldLine = this.getFoldLine(end.row);
var idx = 0;
if (foldLine) {
foldLine.addRemoveChars(end.row, end.column, start.column - end.column);
foldLine.shiftRow(-len);
var foldLineBefore = this.getFoldLine(firstRow);
if (foldLineBefore && foldLineBefore !== foldLine) {
foldLineBefore.merge(foldLine);
foldLine = foldLineBefore;
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= end.row) {
foldLine.shiftRow(-len);
}
}
lastRow = firstRow;
} else {
var args = Array(len);
args.unshift(firstRow, 0);
var arr = useWrapMode ? this.$wrapData : this.$rowLengthCache
arr.splice.apply(arr, args);
var foldLines = this.$foldData;
var foldLine = this.getFoldLine(firstRow);
var idx = 0;
if (foldLine) {
var cmp = foldLine.range.compareInside(start.row, start.column);
if (cmp == 0) {
foldLine = foldLine.split(start.row, start.column);
if (foldLine) {
foldLine.shiftRow(len);
foldLine.addRemoveChars(lastRow, 0, end.column - start.column);
}
} else
if (cmp == -1) {
foldLine.addRemoveChars(firstRow, 0, end.column - start.column);
foldLine.shiftRow(len);
}
idx = foldLines.indexOf(foldLine) + 1;
}
for (idx; idx < foldLines.length; idx++) {
var foldLine = foldLines[idx];
if (foldLine.start.row >= firstRow) {
foldLine.shiftRow(len);
}
}
}
} else {
len = Math.abs(delta.start.column - delta.end.column);
if (action === "remove") {
removedFolds = this.getFoldsInRange(delta);
this.removeFolds(removedFolds);
len = -len;
}
var foldLine = this.getFoldLine(firstRow);
if (foldLine) {
foldLine.addRemoveChars(firstRow, start.column, len);
}
}
if (useWrapMode && this.$wrapData.length != this.doc.getLength()) {
console.error("doc.getLength() and $wrapData.length have to be the same!");
}
this.$updating = false;
if (useWrapMode)
this.$updateWrapData(firstRow, lastRow);
else
this.$updateRowLengthCache(firstRow, lastRow);
return removedFolds;
};
this.$updateRowLengthCache = function(firstRow, lastRow, b) {
this.$rowLengthCache[firstRow] = null;
this.$rowLengthCache[lastRow] = null;
};
this.$updateWrapData = function(firstRow, lastRow) {
var lines = this.doc.getAllLines();
var tabSize = this.getTabSize();
var wrapData = this.$wrapData;
var wrapLimit = this.$wrapLimit;
var tokens;
var foldLine;
var row = firstRow;
lastRow = Math.min(lastRow, lines.length - 1);
while (row <= lastRow) {
foldLine = this.getFoldLine(row, foldLine);
if (!foldLine) {
tokens = this.$getDisplayTokens(lines[row]);
wrapData[row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row ++;
} else {
tokens = [];
foldLine.walk(function(placeholder, row, column, lastColumn) {
var walkTokens;
if (placeholder != null) {
walkTokens = this.$getDisplayTokens(
placeholder, tokens.length);
walkTokens[0] = PLACEHOLDER_START;
for (var i = 1; i < walkTokens.length; i++) {
walkTokens[i] = PLACEHOLDER_BODY;
}
} else {
walkTokens = this.$getDisplayTokens(
lines[row].substring(lastColumn, column),
tokens.length);
}
tokens = tokens.concat(walkTokens);
}.bind(this),
foldLine.end.row,
lines[foldLine.end.row].length + 1
);
wrapData[foldLine.start.row] = this.$computeWrapSplits(tokens, wrapLimit, tabSize);
row = foldLine.end.row + 1;
}
}
};
var CHAR = 1,
CHAR_EXT = 2,
PLACEHOLDER_START = 3,
PLACEHOLDER_BODY = 4,
PUNCTUATION = 9,
SPACE = 10,
TAB = 11,
TAB_SPACE = 12;
this.$computeWrapSplits = function(tokens, wrapLimit, tabSize) {
if (tokens.length == 0) {
return [];
}
var splits = [];
var displayLength = tokens.length;
var lastSplit = 0, lastDocSplit = 0;
var isCode = this.$wrapAsCode;
var indentedSoftWrap = this.$indentedSoftWrap;
var maxIndent = wrapLimit <= Math.max(2 * tabSize, 8)
|| indentedSoftWrap === false ? 0 : Math.floor(wrapLimit / 2);
function getWrapIndent() {
var indentation = 0;
if (maxIndent === 0)
return indentation;
if (indentedSoftWrap) {
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token == SPACE)
indentation += 1;
else if (token == TAB)
indentation += tabSize;
else if (token == TAB_SPACE)
continue;
else
break;
}
}
if (isCode && indentedSoftWrap !== false)
indentation += tabSize;
return Math.min(indentation, maxIndent);
}
function addSplit(screenPos) {
var displayed = tokens.slice(lastSplit, screenPos);
var len = displayed.length;
displayed.join("")
.replace(/12/g, function() {
len -= 1;
})
.replace(/2/g, function() {
len -= 1;
});
if (!splits.length) {
indent = getWrapIndent();
splits.indent = indent;
}
lastDocSplit += len;
splits.push(lastDocSplit);
lastSplit = screenPos;
}
var indent = 0;
while (displayLength - lastSplit > wrapLimit - indent) {
var split = lastSplit + wrapLimit - indent;
if (tokens[split - 1] >= SPACE && tokens[split] >= SPACE) {
addSplit(split);
continue;
}
if (tokens[split] == PLACEHOLDER_START || tokens[split] == PLACEHOLDER_BODY) {
for (split; split != lastSplit - 1; split--) {
if (tokens[split] == PLACEHOLDER_START) {
break;
}
}
if (split > lastSplit) {
addSplit(split);
continue;
}
split = lastSplit + wrapLimit;
for (split; split < tokens.length; split++) {
if (tokens[split] != PLACEHOLDER_BODY) {
break;
}
}
if (split == tokens.length) {
break; // Breaks the while-loop.
}
addSplit(split);
continue;
}
var minSplit = Math.max(split - (wrapLimit -(wrapLimit>>2)), lastSplit - 1);
while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
split --;
}
if (isCode) {
while (split > minSplit && tokens[split] < PLACEHOLDER_START) {
split --;
}
while (split > minSplit && tokens[split] == PUNCTUATION) {
split --;
}
} else {
while (split > minSplit && tokens[split] < SPACE) {
split --;
}
}
if (split > minSplit) {
addSplit(++split);
continue;
}
split = lastSplit + wrapLimit;
if (tokens[split] == CHAR_EXT)
split--;
addSplit(split - indent);
}
return splits;
};
this.$getDisplayTokens = function(str, offset) {
var arr = [];
var tabSize;
offset = offset || 0;
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
if (c == 9) {
tabSize = this.getScreenTabSize(arr.length + offset);
arr.push(TAB);
for (var n = 1; n < tabSize; n++) {
arr.push(TAB_SPACE);
}
}
else if (c == 32) {
arr.push(SPACE);
} else if((c > 39 && c < 48) || (c > 57 && c < 64)) {
arr.push(PUNCTUATION);
}
else if (c >= 0x1100 && isFullWidth(c)) {
arr.push(CHAR, CHAR_EXT);
} else {
arr.push(CHAR);
}
}
return arr;
};
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn == 0)
return [0, 0];
if (maxScreenColumn == null)
maxScreenColumn = Infinity;
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charCodeAt(column);
if (c == 9) {
screenColumn += this.getScreenTabSize(screenColumn);
}
else if (c >= 0x1100 && isFullWidth(c)) {
screenColumn += 2;
} else {
screenColumn += 1;
}
if (screenColumn > maxScreenColumn) {
break;
}
}
return [screenColumn, column];
};
this.lineWidgets = null;
this.getRowLength = function(row) {
if (this.lineWidgets)
var h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
else
h = 0
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1 + h;
} else {
return this.$wrapData[row].length + 1 + h;
}
};
this.getRowLineCount = function(row) {
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1;
} else {
return this.$wrapData[row].length + 1;
}
};
this.getRowWrapIndent = function(screenRow) {
if (this.$useWrapMode) {
var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
var splits = this.$wrapData[pos.row];
return splits.length && splits[0] < pos.column ? splits.indent : 0;
} else {
return 0;
}
}
this.getScreenLastRowColumn = function(screenRow) {
var pos = this.screenToDocumentPosition(screenRow, Number.MAX_VALUE);
return this.documentToScreenColumn(pos.row, pos.column);
};
this.getDocumentLastRowColumn = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.getScreenLastRowColumn(screenRow);
};
this.getDocumentLastRowColumnPosition = function(docRow, docColumn) {
var screenRow = this.documentToScreenRow(docRow, docColumn);
return this.screenToDocumentPosition(screenRow, Number.MAX_VALUE / 10);
};
this.getRowSplitData = function(row) {
if (!this.$useWrapMode) {
return undefined;
} else {
return this.$wrapData[row];
}
};
this.getScreenTabSize = function(screenColumn) {
return this.$tabSize - screenColumn % this.$tabSize;
};
this.screenToDocumentRow = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).row;
};
this.screenToDocumentColumn = function(screenRow, screenColumn) {
return this.screenToDocumentPosition(screenRow, screenColumn).column;
};
this.screenToDocumentPosition = function(screenRow, screenColumn) {
if (screenRow < 0)
return {row: 0, column: 0};
var line;
var docRow = 0;
var docColumn = 0;
var column;
var row = 0;
var rowLength = 0;
var rowCache = this.$screenRowCache;
var i = this.$getRowCacheIndex(rowCache, screenRow);
var l = rowCache.length;
if (l && i >= 0) {
var row = rowCache[i];
var docRow = this.$docRowCache[i];
var doCache = screenRow > rowCache[l - 1];
} else {
var doCache = !l;
}
var maxRow = this.getLength() - 1;
var foldLine = this.getNextFoldLine(docRow);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (row <= screenRow) {
rowLength = this.getRowLength(docRow);
if (row + rowLength > screenRow || docRow >= maxRow) {
break;
} else {
row += rowLength;
docRow++;
if (docRow > foldStart) {
docRow = foldLine.end.row+1;
foldLine = this.getNextFoldLine(docRow, foldLine);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
}
if (doCache) {
this.$docRowCache.push(docRow);
this.$screenRowCache.push(row);
}
}
if (foldLine && foldLine.start.row <= docRow) {
line = this.getFoldDisplayLine(foldLine);
docRow = foldLine.start.row;
} else if (row + rowLength <= screenRow || docRow > maxRow) {
return {
row: maxRow,
column: this.getLine(maxRow).length
};
} else {
line = this.getLine(docRow);
foldLine = null;
}
var wrapIndent = 0;
if (this.$useWrapMode) {
var splits = this.$wrapData[docRow];
if (splits) {
var splitIndex = Math.floor(screenRow - row);
column = splits[splitIndex];
if(splitIndex > 0 && splits.length) {
wrapIndent = splits.indent;
docColumn = splits[splitIndex - 1] || splits[splits.length - 1];
line = line.substring(docColumn);
}
}
}
docColumn += this.$getStringScreenWidth(line, screenColumn - wrapIndent)[1];
if (this.$useWrapMode && docColumn >= column)
docColumn = column - 1;
if (foldLine)
return foldLine.idxToPosition(docColumn);
return {row: docRow, column: docColumn};
};
this.documentToScreenPosition = function(docRow, docColumn) {
if (typeof docColumn === "undefined")
var pos = this.$clipPositionToDocument(docRow.row, docRow.column);
else
pos = this.$clipPositionToDocument(docRow, docColumn);
docRow = pos.row;
docColumn = pos.column;
var screenRow = 0;
var foldStartRow = null;
var fold = null;
fold = this.getFoldAt(docRow, docColumn, 1);
if (fold) {
docRow = fold.start.row;
docColumn = fold.start.column;
}
var rowEnd, row = 0;
var rowCache = this.$docRowCache;
var i = this.$getRowCacheIndex(rowCache, docRow);
var l = rowCache.length;
if (l && i >= 0) {
var row = rowCache[i];
var screenRow = this.$screenRowCache[i];
var doCache = docRow > rowCache[l - 1];
} else {
var doCache = !l;
}
var foldLine = this.getNextFoldLine(row);
var foldStart = foldLine ?foldLine.start.row :Infinity;
while (row < docRow) {
if (row >= foldStart) {
rowEnd = foldLine.end.row + 1;
if (rowEnd > docRow)
break;
foldLine = this.getNextFoldLine(rowEnd, foldLine);
foldStart = foldLine ?foldLine.start.row :Infinity;
}
else {
rowEnd = row + 1;
}
screenRow += this.getRowLength(row);
row = rowEnd;
if (doCache) {
this.$docRowCache.push(row);
this.$screenRowCache.push(screenRow);
}
}
var textLine = "";
if (foldLine && row >= foldStart) {
textLine = this.getFoldDisplayLine(foldLine, docRow, docColumn);
foldStartRow = foldLine.start.row;
} else {
textLine = this.getLine(docRow).substring(0, docColumn);
foldStartRow = docRow;
}
var wrapIndent = 0;
if (this.$useWrapMode) {
var wrapRow = this.$wrapData[foldStartRow];
if (wrapRow) {
var screenRowOffset = 0;
while (textLine.length >= wrapRow[screenRowOffset]) {
screenRow ++;
screenRowOffset++;
}
textLine = textLine.substring(
wrapRow[screenRowOffset - 1] || 0, textLine.length
);
wrapIndent = screenRowOffset > 0 ? wrapRow.indent : 0;
}
}
return {
row: screenRow,
column: wrapIndent + this.$getStringScreenWidth(textLine)[0]
};
};
this.documentToScreenColumn = function(row, docColumn) {
return this.documentToScreenPosition(row, docColumn).column;
};
this.documentToScreenRow = function(docRow, docColumn) {
return this.documentToScreenPosition(docRow, docColumn).row;
};
this.getScreenLength = function() {
var screenRows = 0;
var fold = null;
if (!this.$useWrapMode) {
screenRows = this.getLength();
var foldData = this.$foldData;
for (var i = 0; i < foldData.length; i++) {
fold = foldData[i];
screenRows -= fold.end.row - fold.start.row;
}
} else {
var lastRow = this.$wrapData.length;
var row = 0, i = 0;
var fold = this.$foldData[i++];
var foldStart = fold ? fold.start.row :Infinity;
while (row < lastRow) {
var splits = this.$wrapData[row];
screenRows += splits ? splits.length + 1 : 1;
row ++;
if (row > foldStart) {
row = fold.end.row+1;
fold = this.$foldData[i++];
foldStart = fold ?fold.start.row :Infinity;
}
}
}
if (this.lineWidgets)
screenRows += this.$getWidgetScreenLength();
return screenRows;
};
this.$setFontMetrics = function(fm) {
if (!this.$enableVarChar) return;
this.$getStringScreenWidth = function(str, maxScreenColumn, screenColumn) {
if (maxScreenColumn === 0)
return [0, 0];
if (!maxScreenColumn)
maxScreenColumn = Infinity;
screenColumn = screenColumn || 0;
var c, column;
for (column = 0; column < str.length; column++) {
c = str.charAt(column);
if (c === "\t") {
screenColumn += this.getScreenTabSize(screenColumn);
} else {
screenColumn += fm.getCharacterWidth(c);
}
if (screenColumn > maxScreenColumn) {
break;
}
}
return [screenColumn, column];
};
};
this.destroy = function() {
if (this.bgTokenizer) {
this.bgTokenizer.setDocument(null);
this.bgTokenizer = null;
}
this.$stopWorker();
};
function isFullWidth(c) {
if (c < 0x1100)
return false;
return c >= 0x1100 && c <= 0x115F ||
c >= 0x11A3 && c <= 0x11A7 ||
c >= 0x11FA && c <= 0x11FF ||
c >= 0x2329 && c <= 0x232A ||
c >= 0x2E80 && c <= 0x2E99 ||
c >= 0x2E9B && c <= 0x2EF3 ||
c >= 0x2F00 && c <= 0x2FD5 ||
c >= 0x2FF0 && c <= 0x2FFB ||
c >= 0x3000 && c <= 0x303E ||
c >= 0x3041 && c <= 0x3096 ||
c >= 0x3099 && c <= 0x30FF ||
c >= 0x3105 && c <= 0x312D ||
c >= 0x3131 && c <= 0x318E ||
c >= 0x3190 && c <= 0x31BA ||
c >= 0x31C0 && c <= 0x31E3 ||
c >= 0x31F0 && c <= 0x321E ||
c >= 0x3220 && c <= 0x3247 ||
c >= 0x3250 && c <= 0x32FE ||
c >= 0x3300 && c <= 0x4DBF ||
c >= 0x4E00 && c <= 0xA48C ||
c >= 0xA490 && c <= 0xA4C6 ||
c >= 0xA960 && c <= 0xA97C ||
c >= 0xAC00 && c <= 0xD7A3 ||
c >= 0xD7B0 && c <= 0xD7C6 ||
c >= 0xD7CB && c <= 0xD7FB ||
c >= 0xF900 && c <= 0xFAFF ||
c >= 0xFE10 && c <= 0xFE19 ||
c >= 0xFE30 && c <= 0xFE52 ||
c >= 0xFE54 && c <= 0xFE66 ||
c >= 0xFE68 && c <= 0xFE6B ||
c >= 0xFF01 && c <= 0xFF60 ||
c >= 0xFFE0 && c <= 0xFFE6;
}
}).call(EditSession.prototype);
acequire("./edit_session/folding").Folding.call(EditSession.prototype);
acequire("./edit_session/bracket_match").BracketMatch.call(EditSession.prototype);
config.defineOptions(EditSession.prototype, "session", {
wrap: {
set: function(value) {
if (!value || value == "off")
value = false;
else if (value == "free")
value = true;
else if (value == "printMargin")
value = -1;
else if (typeof value == "string")
value = parseInt(value, 10) || false;
if (this.$wrap == value)
return;
this.$wrap = value;
if (!value) {
this.setUseWrapMode(false);
} else {
var col = typeof value == "number" ? value : null;
this.setWrapLimitRange(col, col);
this.setUseWrapMode(true);
}
},
get: function() {
if (this.getUseWrapMode()) {
if (this.$wrap == -1)
return "printMargin";
if (!this.getWrapLimitRange().min)
return "free";
return this.$wrap;
}
return "off";
},
handlesSet: true
},
wrapMethod: {
set: function(val) {
val = val == "auto"
? this.$mode.type != "text"
: val != "text";
if (val != this.$wrapAsCode) {
this.$wrapAsCode = val;
if (this.$useWrapMode) {
this.$modified = true;
this.$resetRowCache(0);
this.$updateWrapData(0, this.getLength() - 1);
}
}
},
initialValue: "auto"
},
indentedSoftWrap: { initialValue: true },
firstLineNumber: {
set: function() {this._signal("changeBreakpoint");},
initialValue: 1
},
useWorker: {
set: function(useWorker) {
this.$useWorker = useWorker;
this.$stopWorker();
if (useWorker)
this.$startWorker();
},
initialValue: true
},
useSoftTabs: {initialValue: true},
tabSize: {
set: function(tabSize) {
if (isNaN(tabSize) || this.$tabSize === tabSize) return;
this.$modified = true;
this.$rowLengthCache = [];
this.$tabSize = tabSize;
this._signal("changeTabSize");
},
initialValue: 4,
handlesSet: true
},
overwrite: {
set: function(val) {this._signal("changeOverwrite");},
initialValue: false
},
newLineMode: {
set: function(val) {this.doc.setNewLineMode(val)},
get: function() {return this.doc.getNewLineMode()},
handlesSet: true
},
mode: {
set: function(val) { this.setMode(val) },
get: function() { return this.$modeId }
}
});
exports.EditSession = EditSession;
});
ace.define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"], function(acequire, exports, module) {
"use strict";
var lang = acequire("./lib/lang");
var oop = acequire("./lib/oop");
var Range = acequire("./range").Range;
var Search = function() {
this.$options = {};
};
(function() {
this.set = function(options) {
oop.mixin(this.$options, options);
return this;
};
this.getOptions = function() {
return lang.copyObject(this.$options);
};
this.setOptions = function(options) {
this.$options = options;
};
this.find = function(session) {
var options = this.$options;
var iterator = this.$matchIterator(session, options);
if (!iterator)
return false;
var firstRange = null;
iterator.forEach(function(range, row, offset) {
if (!range.start) {
var column = range.offset + (offset || 0);
firstRange = new Range(row, column, row, column + range.length);
if (!range.length && options.start && options.start.start
&& options.skipCurrent != false && firstRange.isEqual(options.start)
) {
firstRange = null;
return false;
}
} else
firstRange = range;
return true;
});
return firstRange;
};
this.findAll = function(session) {
var options = this.$options;
if (!options.needle)
return [];
this.$assembleRegExp(options);
var range = options.range;
var lines = range
? session.getLines(range.start.row, range.end.row)
: session.doc.getAllLines();
var ranges = [];
var re = options.re;
if (options.$isMultiLine) {
var len = re.length;
var maxRow = lines.length - len;
var prevRange;
outer: for (var row = re.offset || 0; row <= maxRow; row++) {
for (var j = 0; j < len; j++)
if (lines[row + j].search(re[j]) == -1)
continue outer;
var startLine = lines[row];
var line = lines[row + len - 1];
var startIndex = startLine.length - startLine.match(re[0])[0].length;
var endIndex = line.match(re[len - 1])[0].length;
if (prevRange && prevRange.end.row === row &&
prevRange.end.column > startIndex
) {
continue;
}
ranges.push(prevRange = new Range(
row, startIndex, row + len - 1, endIndex
));
if (len > 2)
row = row + len - 2;
}
} else {
for (var i = 0; i < lines.length; i++) {
var matches = lang.getMatchOffsets(lines[i], re);
for (var j = 0; j < matches.length; j++) {
var match = matches[j];
ranges.push(new Range(i, match.offset, i, match.offset + match.length));
}
}
}
if (range) {
var startColumn = range.start.column;
var endColumn = range.start.column;
var i = 0, j = ranges.length - 1;
while (i < j && ranges[i].start.column < startColumn && ranges[i].start.row == range.start.row)
i++;
while (i < j && ranges[j].end.column > endColumn && ranges[j].end.row == range.end.row)
j--;
ranges = ranges.slice(i, j + 1);
for (i = 0, j = ranges.length; i < j; i++) {
ranges[i].start.row += range.start.row;
ranges[i].end.row += range.start.row;
}
}
return ranges;
};
this.replace = function(input, replacement) {
var options = this.$options;
var re = this.$assembleRegExp(options);
if (options.$isMultiLine)
return replacement;
if (!re)
return;
var match = re.exec(input);
if (!match || match[0].length != input.length)
return null;
replacement = input.replace(re, replacement);
if (options.preserveCase) {
replacement = replacement.split("");
for (var i = Math.min(input.length, input.length); i--; ) {
var ch = input[i];
if (ch && ch.toLowerCase() != ch)
replacement[i] = replacement[i].toUpperCase();
else
replacement[i] = replacement[i].toLowerCase();
}
replacement = replacement.join("");
}
return replacement;
};
this.$matchIterator = function(session, options) {
var re = this.$assembleRegExp(options);
if (!re)
return false;
var callback;
if (options.$isMultiLine) {
var len = re.length;
var matchIterator = function(line, row, offset) {
var startIndex = line.search(re[0]);
if (startIndex == -1)
return;
for (var i = 1; i < len; i++) {
line = session.getLine(row + i);
if (line.search(re[i]) == -1)
return;
}
var endIndex = line.match(re[len - 1])[0].length;
var range = new Range(row, startIndex, row + len - 1, endIndex);
if (re.offset == 1) {
range.start.row--;
range.start.column = Number.MAX_VALUE;
} else if (offset)
range.start.column += offset;
if (callback(range))
return true;
};
} else if (options.backwards) {
var matchIterator = function(line, row, startIndex) {
var matches = lang.getMatchOffsets(line, re);
for (var i = matches.length-1; i >= 0; i--)
if (callback(matches[i], row, startIndex))
return true;
};
} else {
var matchIterator = function(line, row, startIndex) {
var matches = lang.getMatchOffsets(line, re);
for (var i = 0; i < matches.length; i++)
if (callback(matches[i], row, startIndex))
return true;
};
}
var lineIterator = this.$lineIterator(session, options);
return {
forEach: function(_callback) {
callback = _callback;
lineIterator.forEach(matchIterator);
}
};
};
this.$assembleRegExp = function(options, $disableFakeMultiline) {
if (options.needle instanceof RegExp)
return options.re = options.needle;
var needle = options.needle;
if (!options.needle)
return options.re = false;
if (!options.regExp)
needle = lang.escapeRegExp(needle);
if (options.wholeWord)
needle = addWordBoundary(needle, options);
var modifier = options.caseSensitive ? "gm" : "gmi";
options.$isMultiLine = !$disableFakeMultiline && /[\n\r]/.test(needle);
if (options.$isMultiLine)
return options.re = this.$assembleMultilineRegExp(needle, modifier);
try {
var re = new RegExp(needle, modifier);
} catch(e) {
re = false;
}
return options.re = re;
};
this.$assembleMultilineRegExp = function(needle, modifier) {
var parts = needle.replace(/\r\n|\r|\n/g, "$\n^").split("\n");
var re = [];
for (var i = 0; i < parts.length; i++) try {
re.push(new RegExp(parts[i], modifier));
} catch(e) {
return false;
}
if (parts[0] == "") {
re.shift();
re.offset = 1;
} else {
re.offset = 0;
}
return re;
};
this.$lineIterator = function(session, options) {
var backwards = options.backwards == true;
var skipCurrent = options.skipCurrent != false;
var range = options.range;
var start = options.start;
if (!start)
start = range ? range[backwards ? "end" : "start"] : session.selection.getRange();
if (start.start)
start = start[skipCurrent != backwards ? "end" : "start"];
var firstRow = range ? range.start.row : 0;
var lastRow = range ? range.end.row : session.getLength() - 1;
var forEach = backwards ? function(callback) {
var row = start.row;
var line = session.getLine(row).substring(0, start.column);
if (callback(line, row))
return;
for (row--; row >= firstRow; row--)
if (callback(session.getLine(row), row))
return;
if (options.wrap == false)
return;
for (row = lastRow, firstRow = start.row; row >= firstRow; row--)
if (callback(session.getLine(row), row))
return;
} : function(callback) {
var row = start.row;
var line = session.getLine(row).substr(start.column);
if (callback(line, row, start.column))
return;
for (row = row+1; row <= lastRow; row++)
if (callback(session.getLine(row), row))
return;
if (options.wrap == false)
return;
for (row = firstRow, lastRow = start.row; row <= lastRow; row++)
if (callback(session.getLine(row), row))
return;
};
return {forEach: forEach};
};
}).call(Search.prototype);
function addWordBoundary(needle, options) {
function wordBoundary(c) {
if (/\w/.test(c) || options.regExp) return "\\b";
return "";
}
return wordBoundary(needle[0]) + needle
+ wordBoundary(needle[needle.length - 1]);
}
exports.Search = Search;
});
ace.define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"], function(acequire, exports, module) {
"use strict";
var keyUtil = acequire("../lib/keys");
var useragent = acequire("../lib/useragent");
var KEY_MODS = keyUtil.KEY_MODS;
function HashHandler(config, platform) {
this.platform = platform || (useragent.isMac ? "mac" : "win");
this.commands = {};
this.commandKeyBinding = {};
this.addCommands(config);
this.$singleCommand = true;
}
function MultiHashHandler(config, platform) {
HashHandler.call(this, config, platform);
this.$singleCommand = false;
}
MultiHashHandler.prototype = HashHandler.prototype;
(function() {
this.addCommand = function(command) {
if (this.commands[command.name])
this.removeCommand(command);
this.commands[command.name] = command;
if (command.bindKey)
this._buildKeyHash(command);
};
this.removeCommand = function(command, keepCommand) {
var name = command && (typeof command === 'string' ? command : command.name);
command = this.commands[name];
if (!keepCommand)
delete this.commands[name];
var ckb = this.commandKeyBinding;
for (var keyId in ckb) {
var cmdGroup = ckb[keyId];
if (cmdGroup == command) {
delete ckb[keyId];
} else if (Array.isArray(cmdGroup)) {
var i = cmdGroup.indexOf(command);
if (i != -1) {
cmdGroup.splice(i, 1);
if (cmdGroup.length == 1)
ckb[keyId] = cmdGroup[0];
}
}
}
};
this.bindKey = function(key, command, position) {
if (typeof key == "object" && key) {
if (position == undefined)
position = key.position;
key = key[this.platform];
}
if (!key)
return;
if (typeof command == "function")
return this.addCommand({exec: command, bindKey: key, name: command.name || key});
key.split("|").forEach(function(keyPart) {
var chain = "";
if (keyPart.indexOf(" ") != -1) {
var parts = keyPart.split(/\s+/);
keyPart = parts.pop();
parts.forEach(function(keyPart) {
var binding = this.parseKeys(keyPart);
var id = KEY_MODS[binding.hashId] + binding.key;
chain += (chain ? " " : "") + id;
this._addCommandToBinding(chain, "chainKeys");
}, this);
chain += " ";
}
var binding = this.parseKeys(keyPart);
var id = KEY_MODS[binding.hashId] + binding.key;
this._addCommandToBinding(chain + id, command, position);
}, this);
};
function getPosition(command) {
return typeof command == "object" && command.bindKey
&& command.bindKey.position || 0;
}
this._addCommandToBinding = function(keyId, command, position) {
var ckb = this.commandKeyBinding, i;
if (!command) {
delete ckb[keyId];
} else if (!ckb[keyId] || this.$singleCommand) {
ckb[keyId] = command;
} else {
if (!Array.isArray(ckb[keyId])) {
ckb[keyId] = [ckb[keyId]];
} else if ((i = ckb[keyId].indexOf(command)) != -1) {
ckb[keyId].splice(i, 1);
}
if (typeof position != "number") {
if (position || command.isDefault)
position = -100;
else
position = getPosition(command);
}
var commands = ckb[keyId];
for (i = 0; i < commands.length; i++) {
var other = commands[i];
var otherPos = getPosition(other);
if (otherPos > position)
break;
}
commands.splice(i, 0, command);
}
};
this.addCommands = function(commands) {
commands && Object.keys(commands).forEach(function(name) {
var command = commands[name];
if (!command)
return;
if (typeof command === "string")
return this.bindKey(command, name);
if (typeof command === "function")
command = { exec: command };
if (typeof command !== "object")
return;
if (!command.name)
command.name = name;
this.addCommand(command);
}, this);
};
this.removeCommands = function(commands) {
Object.keys(commands).forEach(function(name) {
this.removeCommand(commands[name]);
}, this);
};
this.bindKeys = function(keyList) {
Object.keys(keyList).forEach(function(key) {
this.bindKey(key, keyList[key]);
}, this);
};
this._buildKeyHash = function(command) {
this.bindKey(command.bindKey, command);
};
this.parseKeys = function(keys) {
var parts = keys.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(x){return x});
var key = parts.pop();
var keyCode = keyUtil[key];
if (keyUtil.FUNCTION_KEYS[keyCode])
key = keyUtil.FUNCTION_KEYS[keyCode].toLowerCase();
else if (!parts.length)
return {key: key, hashId: -1};
else if (parts.length == 1 && parts[0] == "shift")
return {key: key.toUpperCase(), hashId: -1};
var hashId = 0;
for (var i = parts.length; i--;) {
var modifier = keyUtil.KEY_MODS[parts[i]];
if (modifier == null) {
if (typeof console != "undefined")
console.error("invalid modifier " + parts[i] + " in " + keys);
return false;
}
hashId |= modifier;
}
return {key: key, hashId: hashId};
};
this.findKeyCommand = function findKeyCommand(hashId, keyString) {
var key = KEY_MODS[hashId] + keyString;
return this.commandKeyBinding[key];
};
this.handleKeyboard = function(data, hashId, keyString, keyCode) {
if (keyCode < 0) return;
var key = KEY_MODS[hashId] + keyString;
var command = this.commandKeyBinding[key];
if (data.$keyChain) {
data.$keyChain += " " + key;
command = this.commandKeyBinding[data.$keyChain] || command;
}
if (command) {
if (command == "chainKeys" || command[command.length - 1] == "chainKeys") {
data.$keyChain = data.$keyChain || key;
return {command: "null"};
}
}
if (data.$keyChain) {
if ((!hashId || hashId == 4) && keyString.length == 1)
data.$keyChain = data.$keyChain.slice(0, -key.length - 1); // wait for input
else if (hashId == -1 || keyCode > 0)
data.$keyChain = ""; // reset keyChain
}
return {command: command};
};
this.getStatusText = function(editor, data) {
return data.$keyChain || "";
};
}).call(HashHandler.prototype);
exports.HashHandler = HashHandler;
exports.MultiHashHandler = MultiHashHandler;
});
ace.define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var MultiHashHandler = acequire("../keyboard/hash_handler").MultiHashHandler;
var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
var CommandManager = function(platform, commands) {
MultiHashHandler.call(this, commands, platform);
this.byName = this.commands;
this.setDefaultHandler("exec", function(e) {
return e.command.exec(e.editor, e.args || {});
});
};
oop.inherits(CommandManager, MultiHashHandler);
(function() {
oop.implement(this, EventEmitter);
this.exec = function(command, editor, args) {
if (Array.isArray(command)) {
for (var i = command.length; i--; ) {
if (this.exec(command[i], editor, args)) return true;
}
return false;
}
if (typeof command === "string")
command = this.commands[command];
if (!command)
return false;
if (editor && editor.$readOnly && !command.readOnly)
return false;
var e = {editor: editor, command: command, args: args};
e.returnValue = this._emit("exec", e);
this._signal("afterExec", e);
return e.returnValue === false ? false : true;
};
this.toggleRecording = function(editor) {
if (this.$inReplay)
return;
editor && editor._emit("changeStatus");
if (this.recording) {
this.macro.pop();
this.removeEventListener("exec", this.$addCommandToMacro);
if (!this.macro.length)
this.macro = this.oldMacro;
return this.recording = false;
}
if (!this.$addCommandToMacro) {
this.$addCommandToMacro = function(e) {
this.macro.push([e.command, e.args]);
}.bind(this);
}
this.oldMacro = this.macro;
this.macro = [];
this.on("exec", this.$addCommandToMacro);
return this.recording = true;
};
this.replay = function(editor) {
if (this.$inReplay || !this.macro)
return;
if (this.recording)
return this.toggleRecording(editor);
try {
this.$inReplay = true;
this.macro.forEach(function(x) {
if (typeof x == "string")
this.exec(x, editor);
else
this.exec(x[0], editor, x[1]);
}, this);
} finally {
this.$inReplay = false;
}
};
this.trimMacro = function(m) {
return m.map(function(x){
if (typeof x[0] != "string")
x[0] = x[0].name;
if (!x[1])
x = x[0];
return x;
});
};
}).call(CommandManager.prototype);
exports.CommandManager = CommandManager;
});
ace.define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config","ace/range"], function(acequire, exports, module) {
"use strict";
var lang = acequire("../lib/lang");
var config = acequire("../config");
var Range = acequire("../range").Range;
function bindKey(win, mac) {
return {win: win, mac: mac};
}
exports.commands = [{
name: "showSettingsMenu",
bindKey: bindKey("Ctrl-,", "Command-,"),
exec: function(editor) {
config.loadModule("ace/ext/settings_menu", function(module) {
module.init(editor);
editor.showSettingsMenu();
});
},
readOnly: true
}, {
name: "goToNextError",
bindKey: bindKey("Alt-E", "F4"),
exec: function(editor) {
config.loadModule("ace/ext/error_marker", function(module) {
module.showErrorMarker(editor, 1);
});
},
scrollIntoView: "animate",
readOnly: true
}, {
name: "goToPreviousError",
bindKey: bindKey("Alt-Shift-E", "Shift-F4"),
exec: function(editor) {
config.loadModule("ace/ext/error_marker", function(module) {
module.showErrorMarker(editor, -1);
});
},
scrollIntoView: "animate",
readOnly: true
}, {
name: "selectall",
bindKey: bindKey("Ctrl-A", "Command-A"),
exec: function(editor) { editor.selectAll(); },
readOnly: true
}, {
name: "centerselection",
bindKey: bindKey(null, "Ctrl-L"),
exec: function(editor) { editor.centerSelection(); },
readOnly: true
}, {
name: "gotoline",
bindKey: bindKey("Ctrl-L", "Command-L"),
exec: function(editor) {
var line = parseInt(prompt("Enter line number:"), 10);
if (!isNaN(line)) {
editor.gotoLine(line);
}
},
readOnly: true
}, {
name: "fold",
bindKey: bindKey("Alt-L|Ctrl-F1", "Command-Alt-L|Command-F1"),
exec: function(editor) { editor.session.toggleFold(false); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "unfold",
bindKey: bindKey("Alt-Shift-L|Ctrl-Shift-F1", "Command-Alt-Shift-L|Command-Shift-F1"),
exec: function(editor) { editor.session.toggleFold(true); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "toggleFoldWidget",
bindKey: bindKey("F2", "F2"),
exec: function(editor) { editor.session.toggleFoldWidget(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "toggleParentFoldWidget",
bindKey: bindKey("Alt-F2", "Alt-F2"),
exec: function(editor) { editor.session.toggleFoldWidget(true); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "foldall",
bindKey: bindKey(null, "Ctrl-Command-Option-0"),
exec: function(editor) { editor.session.foldAll(); },
scrollIntoView: "center",
readOnly: true
}, {
name: "foldOther",
bindKey: bindKey("Alt-0", "Command-Option-0"),
exec: function(editor) {
editor.session.foldAll();
editor.session.unfold(editor.selection.getAllRanges());
},
scrollIntoView: "center",
readOnly: true
}, {
name: "unfoldall",
bindKey: bindKey("Alt-Shift-0", "Command-Option-Shift-0"),
exec: function(editor) { editor.session.unfold(); },
scrollIntoView: "center",
readOnly: true
}, {
name: "findnext",
bindKey: bindKey("Ctrl-K", "Command-G"),
exec: function(editor) { editor.findNext(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "findprevious",
bindKey: bindKey("Ctrl-Shift-K", "Command-Shift-G"),
exec: function(editor) { editor.findPrevious(); },
multiSelectAction: "forEach",
scrollIntoView: "center",
readOnly: true
}, {
name: "selectOrFindNext",
bindKey: bindKey("Alt-K", "Ctrl-G"),
exec: function(editor) {
if (editor.selection.isEmpty())
editor.selection.selectWord();
else
editor.findNext();
},
readOnly: true
}, {
name: "selectOrFindPrevious",
bindKey: bindKey("Alt-Shift-K", "Ctrl-Shift-G"),
exec: function(editor) {
if (editor.selection.isEmpty())
editor.selection.selectWord();
else
editor.findPrevious();
},
readOnly: true
}, {
name: "find",
bindKey: bindKey("Ctrl-F", "Command-F"),
exec: function(editor) {
config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor)});
},
readOnly: true
}, {
name: "overwrite",
bindKey: "Insert",
exec: function(editor) { editor.toggleOverwrite(); },
readOnly: true
}, {
name: "selecttostart",
bindKey: bindKey("Ctrl-Shift-Home", "Command-Shift-Home|Command-Shift-Up"),
exec: function(editor) { editor.getSelection().selectFileStart(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "gotostart",
bindKey: bindKey("Ctrl-Home", "Command-Home|Command-Up"),
exec: function(editor) { editor.navigateFileStart(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "selectup",
bindKey: bindKey("Shift-Up", "Shift-Up|Ctrl-Shift-P"),
exec: function(editor) { editor.getSelection().selectUp(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "golineup",
bindKey: bindKey("Up", "Up|Ctrl-P"),
exec: function(editor, args) { editor.navigateUp(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttoend",
bindKey: bindKey("Ctrl-Shift-End", "Command-Shift-End|Command-Shift-Down"),
exec: function(editor) { editor.getSelection().selectFileEnd(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "gotoend",
bindKey: bindKey("Ctrl-End", "Command-End|Command-Down"),
exec: function(editor) { editor.navigateFileEnd(); },
multiSelectAction: "forEach",
readOnly: true,
scrollIntoView: "animate",
aceCommandGroup: "fileJump"
}, {
name: "selectdown",
bindKey: bindKey("Shift-Down", "Shift-Down|Ctrl-Shift-N"),
exec: function(editor) { editor.getSelection().selectDown(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "golinedown",
bindKey: bindKey("Down", "Down|Ctrl-N"),
exec: function(editor, args) { editor.navigateDown(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectwordleft",
bindKey: bindKey("Ctrl-Shift-Left", "Option-Shift-Left"),
exec: function(editor) { editor.getSelection().selectWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotowordleft",
bindKey: bindKey("Ctrl-Left", "Option-Left"),
exec: function(editor) { editor.navigateWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttolinestart",
bindKey: bindKey("Alt-Shift-Left", "Command-Shift-Left|Ctrl-Shift-A"),
exec: function(editor) { editor.getSelection().selectLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotolinestart",
bindKey: bindKey("Alt-Left|Home", "Command-Left|Home|Ctrl-A"),
exec: function(editor) { editor.navigateLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectleft",
bindKey: bindKey("Shift-Left", "Shift-Left|Ctrl-Shift-B"),
exec: function(editor) { editor.getSelection().selectLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotoleft",
bindKey: bindKey("Left", "Left|Ctrl-B"),
exec: function(editor, args) { editor.navigateLeft(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectwordright",
bindKey: bindKey("Ctrl-Shift-Right", "Option-Shift-Right"),
exec: function(editor) { editor.getSelection().selectWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotowordright",
bindKey: bindKey("Ctrl-Right", "Option-Right"),
exec: function(editor) { editor.navigateWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selecttolineend",
bindKey: bindKey("Alt-Shift-Right", "Command-Shift-Right|Shift-End|Ctrl-Shift-E"),
exec: function(editor) { editor.getSelection().selectLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotolineend",
bindKey: bindKey("Alt-Right|End", "Command-Right|End|Ctrl-E"),
exec: function(editor) { editor.navigateLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectright",
bindKey: bindKey("Shift-Right", "Shift-Right"),
exec: function(editor) { editor.getSelection().selectRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "gotoright",
bindKey: bindKey("Right", "Right|Ctrl-F"),
exec: function(editor, args) { editor.navigateRight(args.times); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectpagedown",
bindKey: "Shift-PageDown",
exec: function(editor) { editor.selectPageDown(); },
readOnly: true
}, {
name: "pagedown",
bindKey: bindKey(null, "Option-PageDown"),
exec: function(editor) { editor.scrollPageDown(); },
readOnly: true
}, {
name: "gotopagedown",
bindKey: bindKey("PageDown", "PageDown|Ctrl-V"),
exec: function(editor) { editor.gotoPageDown(); },
readOnly: true
}, {
name: "selectpageup",
bindKey: "Shift-PageUp",
exec: function(editor) { editor.selectPageUp(); },
readOnly: true
}, {
name: "pageup",
bindKey: bindKey(null, "Option-PageUp"),
exec: function(editor) { editor.scrollPageUp(); },
readOnly: true
}, {
name: "gotopageup",
bindKey: "PageUp",
exec: function(editor) { editor.gotoPageUp(); },
readOnly: true
}, {
name: "scrollup",
bindKey: bindKey("Ctrl-Up", null),
exec: function(e) { e.renderer.scrollBy(0, -2 * e.renderer.layerConfig.lineHeight); },
readOnly: true
}, {
name: "scrolldown",
bindKey: bindKey("Ctrl-Down", null),
exec: function(e) { e.renderer.scrollBy(0, 2 * e.renderer.layerConfig.lineHeight); },
readOnly: true
}, {
name: "selectlinestart",
bindKey: "Shift-Home",
exec: function(editor) { editor.getSelection().selectLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectlineend",
bindKey: "Shift-End",
exec: function(editor) { editor.getSelection().selectLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "togglerecording",
bindKey: bindKey("Ctrl-Alt-E", "Command-Option-E"),
exec: function(editor) { editor.commands.toggleRecording(editor); },
readOnly: true
}, {
name: "replaymacro",
bindKey: bindKey("Ctrl-Shift-E", "Command-Shift-E"),
exec: function(editor) { editor.commands.replay(editor); },
readOnly: true
}, {
name: "jumptomatching",
bindKey: bindKey("Ctrl-P", "Ctrl-P"),
exec: function(editor) { editor.jumpToMatching(); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "selecttomatching",
bindKey: bindKey("Ctrl-Shift-P", "Ctrl-Shift-P"),
exec: function(editor) { editor.jumpToMatching(true); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "expandToMatching",
bindKey: bindKey("Ctrl-Shift-M", "Ctrl-Shift-M"),
exec: function(editor) { editor.jumpToMatching(true, true); },
multiSelectAction: "forEach",
scrollIntoView: "animate",
readOnly: true
}, {
name: "passKeysToBrowser",
bindKey: bindKey(null, null),
exec: function() {},
passEvent: true,
readOnly: true
}, {
name: "copy",
exec: function(editor) {
},
readOnly: true
},
{
name: "cut",
exec: function(editor) {
var range = editor.getSelectionRange();
editor._emit("cut", range);
if (!editor.selection.isEmpty()) {
editor.session.remove(range);
editor.clearSelection();
}
},
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "paste",
exec: function(editor, args) {
editor.$handlePaste(args);
},
scrollIntoView: "cursor"
}, {
name: "removeline",
bindKey: bindKey("Ctrl-D", "Command-D"),
exec: function(editor) { editor.removeLines(); },
scrollIntoView: "cursor",
multiSelectAction: "forEachLine"
}, {
name: "duplicateSelection",
bindKey: bindKey("Ctrl-Shift-D", "Command-Shift-D"),
exec: function(editor) { editor.duplicateSelection(); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "sortlines",
bindKey: bindKey("Ctrl-Alt-S", "Command-Alt-S"),
exec: function(editor) { editor.sortLines(); },
scrollIntoView: "selection",
multiSelectAction: "forEachLine"
}, {
name: "togglecomment",
bindKey: bindKey("Ctrl-/", "Command-/"),
exec: function(editor) { editor.toggleCommentLines(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "toggleBlockComment",
bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"),
exec: function(editor) { editor.toggleBlockComment(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "modifyNumberUp",
bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"),
exec: function(editor) { editor.modifyNumber(1); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "modifyNumberDown",
bindKey: bindKey("Ctrl-Shift-Down", "Alt-Shift-Down"),
exec: function(editor) { editor.modifyNumber(-1); },
scrollIntoView: "cursor",
multiSelectAction: "forEach"
}, {
name: "replace",
bindKey: bindKey("Ctrl-H", "Command-Option-F"),
exec: function(editor) {
config.loadModule("ace/ext/searchbox", function(e) {e.Search(editor, true)});
}
}, {
name: "undo",
bindKey: bindKey("Ctrl-Z", "Command-Z"),
exec: function(editor) { editor.undo(); }
}, {
name: "redo",
bindKey: bindKey("Ctrl-Shift-Z|Ctrl-Y", "Command-Shift-Z|Command-Y"),
exec: function(editor) { editor.redo(); }
}, {
name: "copylinesup",
bindKey: bindKey("Alt-Shift-Up", "Command-Option-Up"),
exec: function(editor) { editor.copyLinesUp(); },
scrollIntoView: "cursor"
}, {
name: "movelinesup",
bindKey: bindKey("Alt-Up", "Option-Up"),
exec: function(editor) { editor.moveLinesUp(); },
scrollIntoView: "cursor"
}, {
name: "copylinesdown",
bindKey: bindKey("Alt-Shift-Down", "Command-Option-Down"),
exec: function(editor) { editor.copyLinesDown(); },
scrollIntoView: "cursor"
}, {
name: "movelinesdown",
bindKey: bindKey("Alt-Down", "Option-Down"),
exec: function(editor) { editor.moveLinesDown(); },
scrollIntoView: "cursor"
}, {
name: "del",
bindKey: bindKey("Delete", "Delete|Ctrl-D|Shift-Delete"),
exec: function(editor) { editor.remove("right"); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "backspace",
bindKey: bindKey(
"Shift-Backspace|Backspace",
"Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"
),
exec: function(editor) { editor.remove("left"); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "cut_or_delete",
bindKey: bindKey("Shift-Delete", null),
exec: function(editor) {
if (editor.selection.isEmpty()) {
editor.remove("left");
} else {
return false;
}
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolinestart",
bindKey: bindKey("Alt-Backspace", "Command-Backspace"),
exec: function(editor) { editor.removeToLineStart(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removetolineend",
bindKey: bindKey("Alt-Delete", "Ctrl-K"),
exec: function(editor) { editor.removeToLineEnd(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removewordleft",
bindKey: bindKey("Ctrl-Backspace", "Alt-Backspace|Ctrl-Alt-Backspace"),
exec: function(editor) { editor.removeWordLeft(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "removewordright",
bindKey: bindKey("Ctrl-Delete", "Alt-Delete"),
exec: function(editor) { editor.removeWordRight(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "outdent",
bindKey: bindKey("Shift-Tab", "Shift-Tab"),
exec: function(editor) { editor.blockOutdent(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "indent",
bindKey: bindKey("Tab", "Tab"),
exec: function(editor) { editor.indent(); },
multiSelectAction: "forEach",
scrollIntoView: "selectionPart"
}, {
name: "blockoutdent",
bindKey: bindKey("Ctrl-[", "Ctrl-["),
exec: function(editor) { editor.blockOutdent(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "blockindent",
bindKey: bindKey("Ctrl-]", "Ctrl-]"),
exec: function(editor) { editor.blockIndent(); },
multiSelectAction: "forEachLine",
scrollIntoView: "selectionPart"
}, {
name: "insertstring",
exec: function(editor, str) { editor.insert(str); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "inserttext",
exec: function(editor, args) {
editor.insert(lang.stringRepeat(args.text || "", args.times || 1));
},
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "splitline",
bindKey: bindKey(null, "Ctrl-O"),
exec: function(editor) { editor.splitLine(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "transposeletters",
bindKey: bindKey("Ctrl-T", "Ctrl-T"),
exec: function(editor) { editor.transposeLetters(); },
multiSelectAction: function(editor) {editor.transposeSelections(1); },
scrollIntoView: "cursor"
}, {
name: "touppercase",
bindKey: bindKey("Ctrl-U", "Ctrl-U"),
exec: function(editor) { editor.toUpperCase(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "tolowercase",
bindKey: bindKey("Ctrl-Shift-U", "Ctrl-Shift-U"),
exec: function(editor) { editor.toLowerCase(); },
multiSelectAction: "forEach",
scrollIntoView: "cursor"
}, {
name: "expandtoline",
bindKey: bindKey("Ctrl-Shift-L", "Command-Shift-L"),
exec: function(editor) {
var range = editor.selection.getRange();
range.start.column = range.end.column = 0;
range.end.row++;
editor.selection.setRange(range, false);
},
multiSelectAction: "forEach",
scrollIntoView: "cursor",
readOnly: true
}, {
name: "joinlines",
bindKey: bindKey(null, null),
exec: function(editor) {
var isBackwards = editor.selection.isBackwards();
var selectionStart = isBackwards ? editor.selection.getSelectionLead() : editor.selection.getSelectionAnchor();
var selectionEnd = isBackwards ? editor.selection.getSelectionAnchor() : editor.selection.getSelectionLead();
var firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length;
var selectedText = editor.session.doc.getTextRange(editor.selection.getRange());
var selectedCount = selectedText.replace(/\n\s*/, " ").length;
var insertLine = editor.session.doc.getLine(selectionStart.row);
for (var i = selectionStart.row + 1; i <= selectionEnd.row + 1; i++) {
var curLine = lang.stringTrimLeft(lang.stringTrimRight(editor.session.doc.getLine(i)));
if (curLine.length !== 0) {
curLine = " " + curLine;
}
insertLine += curLine;
}
if (selectionEnd.row + 1 < (editor.session.doc.getLength() - 1)) {
insertLine += editor.session.doc.getNewLineCharacter();
}
editor.clearSelection();
editor.session.doc.replace(new Range(selectionStart.row, 0, selectionEnd.row + 2, 0), insertLine);
if (selectedCount > 0) {
editor.selection.moveCursorTo(selectionStart.row, selectionStart.column);
editor.selection.selectTo(selectionStart.row, selectionStart.column + selectedCount);
} else {
firstLineEndCol = editor.session.doc.getLine(selectionStart.row).length > firstLineEndCol ? (firstLineEndCol + 1) : firstLineEndCol;
editor.selection.moveCursorTo(selectionStart.row, firstLineEndCol);
}
},
multiSelectAction: "forEach",
readOnly: true
}, {
name: "invertSelection",
bindKey: bindKey(null, null),
exec: function(editor) {
var endRow = editor.session.doc.getLength() - 1;
var endCol = editor.session.doc.getLine(endRow).length;
var ranges = editor.selection.rangeList.ranges;
var newRanges = [];
if (ranges.length < 1) {
ranges = [editor.selection.getRange()];
}
for (var i = 0; i < ranges.length; i++) {
if (i == (ranges.length - 1)) {
if (!(ranges[i].end.row === endRow && ranges[i].end.column === endCol)) {
newRanges.push(new Range(ranges[i].end.row, ranges[i].end.column, endRow, endCol));
}
}
if (i === 0) {
if (!(ranges[i].start.row === 0 && ranges[i].start.column === 0)) {
newRanges.push(new Range(0, 0, ranges[i].start.row, ranges[i].start.column));
}
} else {
newRanges.push(new Range(ranges[i-1].end.row, ranges[i-1].end.column, ranges[i].start.row, ranges[i].start.column));
}
}
editor.exitMultiSelectMode();
editor.clearSelection();
for(var i = 0; i < newRanges.length; i++) {
editor.selection.addRange(newRanges[i], false);
}
},
readOnly: true,
scrollIntoView: "none"
}];
});
ace.define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config","ace/token_iterator"], function(acequire, exports, module) {
"use strict";
acequire("./lib/fixoldbrowsers");
var oop = acequire("./lib/oop");
var dom = acequire("./lib/dom");
var lang = acequire("./lib/lang");
var useragent = acequire("./lib/useragent");
var TextInput = acequire("./keyboard/textinput").TextInput;
var MouseHandler = acequire("./mouse/mouse_handler").MouseHandler;
var FoldHandler = acequire("./mouse/fold_handler").FoldHandler;
var KeyBinding = acequire("./keyboard/keybinding").KeyBinding;
var EditSession = acequire("./edit_session").EditSession;
var Search = acequire("./search").Search;
var Range = acequire("./range").Range;
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var CommandManager = acequire("./commands/command_manager").CommandManager;
var defaultCommands = acequire("./commands/default_commands").commands;
var config = acequire("./config");
var TokenIterator = acequire("./token_iterator").TokenIterator;
var Editor = function(renderer, session) {
var container = renderer.getContainerElement();
this.container = container;
this.renderer = renderer;
this.commands = new CommandManager(useragent.isMac ? "mac" : "win", defaultCommands);
this.textInput = new TextInput(renderer.getTextAreaContainer(), this);
this.renderer.textarea = this.textInput.getElement();
this.keyBinding = new KeyBinding(this);
this.$mouseHandler = new MouseHandler(this);
new FoldHandler(this);
this.$blockScrolling = 0;
this.$search = new Search().set({
wrap: true
});
this.$historyTracker = this.$historyTracker.bind(this);
this.commands.on("exec", this.$historyTracker);
this.$initOperationListeners();
this._$emitInputEvent = lang.delayedCall(function() {
this._signal("input", {});
if (this.session && this.session.bgTokenizer)
this.session.bgTokenizer.scheduleStart();
}.bind(this));
this.on("change", function(_, _self) {
_self._$emitInputEvent.schedule(31);
});
this.setSession(session || new EditSession(""));
config.resetOptions(this);
config._signal("editor", this);
};
(function(){
oop.implement(this, EventEmitter);
this.$initOperationListeners = function() {
function last(a) {return a[a.length - 1]}
this.selections = [];
this.commands.on("exec", this.startOperation.bind(this), true);
this.commands.on("afterExec", this.endOperation.bind(this), true);
this.$opResetTimer = lang.delayedCall(this.endOperation.bind(this));
this.on("change", function() {
this.curOp || this.startOperation();
this.curOp.docChanged = true;
}.bind(this), true);
this.on("changeSelection", function() {
this.curOp || this.startOperation();
this.curOp.selectionChanged = true;
}.bind(this), true);
};
this.curOp = null;
this.prevOp = {};
this.startOperation = function(commadEvent) {
if (this.curOp) {
if (!commadEvent || this.curOp.command)
return;
this.prevOp = this.curOp;
}
if (!commadEvent) {
this.previousCommand = null;
commadEvent = {};
}
this.$opResetTimer.schedule();
this.curOp = {
command: commadEvent.command || {},
args: commadEvent.args,
scrollTop: this.renderer.scrollTop
};
if (this.curOp.command.name && this.curOp.command.scrollIntoView !== undefined)
this.$blockScrolling++;
};
this.endOperation = function(e) {
if (this.curOp) {
if (e && e.returnValue === false)
return this.curOp = null;
this._signal("beforeEndOperation");
var command = this.curOp.command;
if (command.name && this.$blockScrolling > 0)
this.$blockScrolling--;
var scrollIntoView = command && command.scrollIntoView;
if (scrollIntoView) {
switch (scrollIntoView) {
case "center-animate":
scrollIntoView = "animate";
case "center":
this.renderer.scrollCursorIntoView(null, 0.5);
break;
case "animate":
case "cursor":
this.renderer.scrollCursorIntoView();
break;
case "selectionPart":
var range = this.selection.getRange();
var config = this.renderer.layerConfig;
if (range.start.row >= config.lastRow || range.end.row <= config.firstRow) {
this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead);
}
break;
default:
break;
}
if (scrollIntoView == "animate")
this.renderer.animateScrolling(this.curOp.scrollTop);
}
this.prevOp = this.curOp;
this.curOp = null;
}
};
this.$mergeableCommands = ["backspace", "del", "insertstring"];
this.$historyTracker = function(e) {
if (!this.$mergeUndoDeltas)
return;
var prev = this.prevOp;
var mergeableCommands = this.$mergeableCommands;
var shouldMerge = prev.command && (e.command.name == prev.command.name);
if (e.command.name == "insertstring") {
var text = e.args;
if (this.mergeNextCommand === undefined)
this.mergeNextCommand = true;
shouldMerge = shouldMerge
&& this.mergeNextCommand // previous command allows to coalesce with
&& (!/\s/.test(text) || /\s/.test(prev.args)); // previous insertion was of same type
this.mergeNextCommand = true;
} else {
shouldMerge = shouldMerge
&& mergeableCommands.indexOf(e.command.name) !== -1; // the command is mergeable
}
if (
this.$mergeUndoDeltas != "always"
&& Date.now() - this.sequenceStartTime > 2000
) {
shouldMerge = false; // the sequence is too long
}
if (shouldMerge)
this.session.mergeUndoDeltas = true;
else if (mergeableCommands.indexOf(e.command.name) !== -1)
this.sequenceStartTime = Date.now();
};
this.setKeyboardHandler = function(keyboardHandler, cb) {
if (keyboardHandler && typeof keyboardHandler === "string") {
this.$keybindingId = keyboardHandler;
var _self = this;
config.loadModule(["keybinding", keyboardHandler], function(module) {
if (_self.$keybindingId == keyboardHandler)
_self.keyBinding.setKeyboardHandler(module && module.handler);
cb && cb();
});
} else {
this.$keybindingId = null;
this.keyBinding.setKeyboardHandler(keyboardHandler);
cb && cb();
}
};
this.getKeyboardHandler = function() {
return this.keyBinding.getKeyboardHandler();
};
this.setSession = function(session) {
if (this.session == session)
return;
if (this.curOp) this.endOperation();
this.curOp = {};
var oldSession = this.session;
if (oldSession) {
this.session.off("change", this.$onDocumentChange);
this.session.off("changeMode", this.$onChangeMode);
this.session.off("tokenizerUpdate", this.$onTokenizerUpdate);
this.session.off("changeTabSize", this.$onChangeTabSize);
this.session.off("changeWrapLimit", this.$onChangeWrapLimit);
this.session.off("changeWrapMode", this.$onChangeWrapMode);
this.session.off("changeFold", this.$onChangeFold);
this.session.off("changeFrontMarker", this.$onChangeFrontMarker);
this.session.off("changeBackMarker", this.$onChangeBackMarker);
this.session.off("changeBreakpoint", this.$onChangeBreakpoint);
this.session.off("changeAnnotation", this.$onChangeAnnotation);
this.session.off("changeOverwrite", this.$onCursorChange);
this.session.off("changeScrollTop", this.$onScrollTopChange);
this.session.off("changeScrollLeft", this.$onScrollLeftChange);
var selection = this.session.getSelection();
selection.off("changeCursor", this.$onCursorChange);
selection.off("changeSelection", this.$onSelectionChange);
}
this.session = session;
if (session) {
this.$onDocumentChange = this.onDocumentChange.bind(this);
session.on("change", this.$onDocumentChange);
this.renderer.setSession(session);
this.$onChangeMode = this.onChangeMode.bind(this);
session.on("changeMode", this.$onChangeMode);
this.$onTokenizerUpdate = this.onTokenizerUpdate.bind(this);
session.on("tokenizerUpdate", this.$onTokenizerUpdate);
this.$onChangeTabSize = this.renderer.onChangeTabSize.bind(this.renderer);
session.on("changeTabSize", this.$onChangeTabSize);
this.$onChangeWrapLimit = this.onChangeWrapLimit.bind(this);
session.on("changeWrapLimit", this.$onChangeWrapLimit);
this.$onChangeWrapMode = this.onChangeWrapMode.bind(this);
session.on("changeWrapMode", this.$onChangeWrapMode);
this.$onChangeFold = this.onChangeFold.bind(this);
session.on("changeFold", this.$onChangeFold);
this.$onChangeFrontMarker = this.onChangeFrontMarker.bind(this);
this.session.on("changeFrontMarker", this.$onChangeFrontMarker);
this.$onChangeBackMarker = this.onChangeBackMarker.bind(this);
this.session.on("changeBackMarker", this.$onChangeBackMarker);
this.$onChangeBreakpoint = this.onChangeBreakpoint.bind(this);
this.session.on("changeBreakpoint", this.$onChangeBreakpoint);
this.$onChangeAnnotation = this.onChangeAnnotation.bind(this);
this.session.on("changeAnnotation", this.$onChangeAnnotation);
this.$onCursorChange = this.onCursorChange.bind(this);
this.session.on("changeOverwrite", this.$onCursorChange);
this.$onScrollTopChange = this.onScrollTopChange.bind(this);
this.session.on("changeScrollTop", this.$onScrollTopChange);
this.$onScrollLeftChange = this.onScrollLeftChange.bind(this);
this.session.on("changeScrollLeft", this.$onScrollLeftChange);
this.selection = session.getSelection();
this.selection.on("changeCursor", this.$onCursorChange);
this.$onSelectionChange = this.onSelectionChange.bind(this);
this.selection.on("changeSelection", this.$onSelectionChange);
this.onChangeMode();
this.$blockScrolling += 1;
this.onCursorChange();
this.$blockScrolling -= 1;
this.onScrollTopChange();
this.onScrollLeftChange();
this.onSelectionChange();
this.onChangeFrontMarker();
this.onChangeBackMarker();
this.onChangeBreakpoint();
this.onChangeAnnotation();
this.session.getUseWrapMode() && this.renderer.adjustWrapLimit();
this.renderer.updateFull();
} else {
this.selection = null;
this.renderer.setSession(session);
}
this._signal("changeSession", {
session: session,
oldSession: oldSession
});
this.curOp = null;
oldSession && oldSession._signal("changeEditor", {oldEditor: this});
session && session._signal("changeEditor", {editor: this});
};
this.getSession = function() {
return this.session;
};
this.setValue = function(val, cursorPos) {
this.session.doc.setValue(val);
if (!cursorPos)
this.selectAll();
else if (cursorPos == 1)
this.navigateFileEnd();
else if (cursorPos == -1)
this.navigateFileStart();
return val;
};
this.getValue = function() {
return this.session.getValue();
};
this.getSelection = function() {
return this.selection;
};
this.resize = function(force) {
this.renderer.onResize(force);
};
this.setTheme = function(theme, cb) {
this.renderer.setTheme(theme, cb);
};
this.getTheme = function() {
return this.renderer.getTheme();
};
this.setStyle = function(style) {
this.renderer.setStyle(style);
};
this.unsetStyle = function(style) {
this.renderer.unsetStyle(style);
};
this.getFontSize = function () {
return this.getOption("fontSize") ||
dom.computedStyle(this.container, "fontSize");
};
this.setFontSize = function(size) {
this.setOption("fontSize", size);
};
this.$highlightBrackets = function() {
if (this.session.$bracketHighlight) {
this.session.removeMarker(this.session.$bracketHighlight);
this.session.$bracketHighlight = null;
}
if (this.$highlightPending) {
return;
}
var self = this;
this.$highlightPending = true;
setTimeout(function() {
self.$highlightPending = false;
var session = self.session;
if (!session || !session.bgTokenizer) return;
var pos = session.findMatchingBracket(self.getCursorPosition());
if (pos) {
var range = new Range(pos.row, pos.column, pos.row, pos.column + 1);
} else if (session.$mode.getMatching) {
var range = session.$mode.getMatching(self.session);
}
if (range)
session.$bracketHighlight = session.addMarker(range, "ace_bracket", "text");
}, 50);
};
this.$highlightTags = function() {
if (this.$highlightTagPending)
return;
var self = this;
this.$highlightTagPending = true;
setTimeout(function() {
self.$highlightTagPending = false;
var session = self.session;
if (!session || !session.bgTokenizer) return;
var pos = self.getCursorPosition();
var iterator = new TokenIterator(self.session, pos.row, pos.column);
var token = iterator.getCurrentToken();
if (!token || !/\b(?:tag-open|tag-name)/.test(token.type)) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
return;
}
if (token.type.indexOf("tag-open") != -1) {
token = iterator.stepForward();
if (!token)
return;
}
var tag = token.value;
var depth = 0;
var prevToken = iterator.stepBackward();
if (prevToken.value == '<'){
do {
prevToken = token;
token = iterator.stepForward();
if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<'){
depth++;
} else if (prevToken.value === '</'){
depth--;
}
}
} while (token && depth >= 0);
} else {
do {
token = prevToken;
prevToken = iterator.stepBackward();
if (token && token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<') {
depth++;
} else if (prevToken.value === '</') {
depth--;
}
}
} while (prevToken && depth <= 0);
iterator.stepForward();
}
if (!token) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
return;
}
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn();
var range = new Range(row, column, row, column+token.value.length);
var sbm = session.$backMarkers[session.$tagHighlight];
if (session.$tagHighlight && sbm != undefined && range.compareRange(sbm.range) !== 0) {
session.removeMarker(session.$tagHighlight);
session.$tagHighlight = null;
}
if (range && !session.$tagHighlight)
session.$tagHighlight = session.addMarker(range, "ace_bracket", "text");
}, 50);
};
this.focus = function() {
var _self = this;
setTimeout(function() {
_self.textInput.focus();
});
this.textInput.focus();
};
this.isFocused = function() {
return this.textInput.isFocused();
};
this.blur = function() {
this.textInput.blur();
};
this.onFocus = function(e) {
if (this.$isFocused)
return;
this.$isFocused = true;
this.renderer.showCursor();
this.renderer.visualizeFocus();
this._emit("focus", e);
};
this.onBlur = function(e) {
if (!this.$isFocused)
return;
this.$isFocused = false;
this.renderer.hideCursor();
this.renderer.visualizeBlur();
this._emit("blur", e);
};
this.$cursorChange = function() {
this.renderer.updateCursor();
};
this.onDocumentChange = function(delta) {
var wrap = this.session.$useWrapMode;
var lastRow = (delta.start.row == delta.end.row ? delta.end.row : Infinity);
this.renderer.updateLines(delta.start.row, lastRow, wrap);
this._signal("change", delta);
this.$cursorChange();
this.$updateHighlightActiveLine();
};
this.onTokenizerUpdate = function(e) {
var rows = e.data;
this.renderer.updateLines(rows.first, rows.last);
};
this.onScrollTopChange = function() {
this.renderer.scrollToY(this.session.getScrollTop());
};
this.onScrollLeftChange = function() {
this.renderer.scrollToX(this.session.getScrollLeft());
};
this.onCursorChange = function() {
this.$cursorChange();
if (!this.$blockScrolling) {
config.warn("Automatically scrolling cursor into view after selection change",
"this will be disabled in the next version",
"set editor.$blockScrolling = Infinity to disable this message"
);
this.renderer.scrollCursorIntoView();
}
this.$highlightBrackets();
this.$highlightTags();
this.$updateHighlightActiveLine();
this._signal("changeSelection");
};
this.$updateHighlightActiveLine = function() {
var session = this.getSession();
var highlight;
if (this.$highlightActiveLine) {
if ((this.$selectionStyle != "line" || !this.selection.isMultiLine()))
highlight = this.getCursorPosition();
if (this.renderer.$maxLines && this.session.getLength() === 1 && !(this.renderer.$minLines > 1))
highlight = false;
}
if (session.$highlightLineMarker && !highlight) {
session.removeMarker(session.$highlightLineMarker.id);
session.$highlightLineMarker = null;
} else if (!session.$highlightLineMarker && highlight) {
var range = new Range(highlight.row, highlight.column, highlight.row, Infinity);
range.id = session.addMarker(range, "ace_active-line", "screenLine");
session.$highlightLineMarker = range;
} else if (highlight) {
session.$highlightLineMarker.start.row = highlight.row;
session.$highlightLineMarker.end.row = highlight.row;
session.$highlightLineMarker.start.column = highlight.column;
session._signal("changeBackMarker");
}
};
this.onSelectionChange = function(e) {
var session = this.session;
if (session.$selectionMarker) {
session.removeMarker(session.$selectionMarker);
}
session.$selectionMarker = null;
if (!this.selection.isEmpty()) {
var range = this.selection.getRange();
var style = this.getSelectionStyle();
session.$selectionMarker = session.addMarker(range, "ace_selection", style);
} else {
this.$updateHighlightActiveLine();
}
var re = this.$highlightSelectedWord && this.$getSelectionHighLightRegexp();
this.session.highlight(re);
this._signal("changeSelection");
};
this.$getSelectionHighLightRegexp = function() {
var session = this.session;
var selection = this.getSelectionRange();
if (selection.isEmpty() || selection.isMultiLine())
return;
var startOuter = selection.start.column - 1;
var endOuter = selection.end.column + 1;
var line = session.getLine(selection.start.row);
var lineCols = line.length;
var needle = line.substring(Math.max(startOuter, 0),
Math.min(endOuter, lineCols));
if ((startOuter >= 0 && /^[\w\d]/.test(needle)) ||
(endOuter <= lineCols && /[\w\d]$/.test(needle)))
return;
needle = line.substring(selection.start.column, selection.end.column);
if (!/^[\w\d]+$/.test(needle))
return;
var re = this.$search.$assembleRegExp({
wholeWord: true,
caseSensitive: true,
needle: needle
});
return re;
};
this.onChangeFrontMarker = function() {
this.renderer.updateFrontMarkers();
};
this.onChangeBackMarker = function() {
this.renderer.updateBackMarkers();
};
this.onChangeBreakpoint = function() {
this.renderer.updateBreakpoints();
};
this.onChangeAnnotation = function() {
this.renderer.setAnnotations(this.session.getAnnotations());
};
this.onChangeMode = function(e) {
this.renderer.updateText();
this._emit("changeMode", e);
};
this.onChangeWrapLimit = function() {
this.renderer.updateFull();
};
this.onChangeWrapMode = function() {
this.renderer.onResize(true);
};
this.onChangeFold = function() {
this.$updateHighlightActiveLine();
this.renderer.updateFull();
};
this.getSelectedText = function() {
return this.session.getTextRange(this.getSelectionRange());
};
this.getCopyText = function() {
var text = this.getSelectedText();
this._signal("copy", text);
return text;
};
this.onCopy = function() {
this.commands.exec("copy", this);
};
this.onCut = function() {
this.commands.exec("cut", this);
};
this.onPaste = function(text, event) {
var e = {text: text, event: event};
this.commands.exec("paste", this, e);
};
this.$handlePaste = function(e) {
if (typeof e == "string")
e = {text: e};
this._signal("paste", e);
var text = e.text;
if (!this.inMultiSelectMode || this.inVirtualSelectionMode) {
this.insert(text);
} else {
var lines = text.split(/\r\n|\r|\n/);
var ranges = this.selection.rangeList.ranges;
if (lines.length > ranges.length || lines.length < 2 || !lines[1])
return this.commands.exec("insertstring", this, text);
for (var i = ranges.length; i--;) {
var range = ranges[i];
if (!range.isEmpty())
this.session.remove(range);
this.session.insert(range.start, lines[i]);
}
}
};
this.execCommand = function(command, args) {
return this.commands.exec(command, this, args);
};
this.insert = function(text, pasted) {
var session = this.session;
var mode = session.getMode();
var cursor = this.getCursorPosition();
if (this.getBehavioursEnabled() && !pasted) {
var transform = mode.transformAction(session.getState(cursor.row), 'insertion', this, session, text);
if (transform) {
if (text !== transform.text) {
this.session.mergeUndoDeltas = false;
this.$mergeNextCommand = false;
}
text = transform.text;
}
}
if (text == "\t")
text = this.session.getTabString();
if (!this.selection.isEmpty()) {
var range = this.getSelectionRange();
cursor = this.session.remove(range);
this.clearSelection();
}
else if (this.session.getOverwrite()) {
var range = new Range.fromPoints(cursor, cursor);
range.end.column += text.length;
this.session.remove(range);
}
if (text == "\n" || text == "\r\n") {
var line = session.getLine(cursor.row);
if (cursor.column > line.search(/\S|$/)) {
var d = line.substr(cursor.column).search(/\S|$/);
session.doc.removeInLine(cursor.row, cursor.column, cursor.column + d);
}
}
this.clearSelection();
var start = cursor.column;
var lineState = session.getState(cursor.row);
var line = session.getLine(cursor.row);
var shouldOutdent = mode.checkOutdent(lineState, line, text);
var end = session.insert(cursor, text);
if (transform && transform.selection) {
if (transform.selection.length == 2) { // Transform relative to the current column
this.selection.setSelectionRange(
new Range(cursor.row, start + transform.selection[0],
cursor.row, start + transform.selection[1]));
} else { // Transform relative to the current row.
this.selection.setSelectionRange(
new Range(cursor.row + transform.selection[0],
transform.selection[1],
cursor.row + transform.selection[2],
transform.selection[3]));
}
}
if (session.getDocument().isNewLine(text)) {
var lineIndent = mode.getNextLineIndent(lineState, line.slice(0, cursor.column), session.getTabString());
session.insert({row: cursor.row+1, column: 0}, lineIndent);
}
if (shouldOutdent)
mode.autoOutdent(lineState, session, cursor.row);
};
this.onTextInput = function(text) {
this.keyBinding.onTextInput(text);
};
this.onCommandKey = function(e, hashId, keyCode) {
this.keyBinding.onCommandKey(e, hashId, keyCode);
};
this.setOverwrite = function(overwrite) {
this.session.setOverwrite(overwrite);
};
this.getOverwrite = function() {
return this.session.getOverwrite();
};
this.toggleOverwrite = function() {
this.session.toggleOverwrite();
};
this.setScrollSpeed = function(speed) {
this.setOption("scrollSpeed", speed);
};
this.getScrollSpeed = function() {
return this.getOption("scrollSpeed");
};
this.setDragDelay = function(dragDelay) {
this.setOption("dragDelay", dragDelay);
};
this.getDragDelay = function() {
return this.getOption("dragDelay");
};
this.setSelectionStyle = function(val) {
this.setOption("selectionStyle", val);
};
this.getSelectionStyle = function() {
return this.getOption("selectionStyle");
};
this.setHighlightActiveLine = function(shouldHighlight) {
this.setOption("highlightActiveLine", shouldHighlight);
};
this.getHighlightActiveLine = function() {
return this.getOption("highlightActiveLine");
};
this.setHighlightGutterLine = function(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
};
this.getHighlightGutterLine = function() {
return this.getOption("highlightGutterLine");
};
this.setHighlightSelectedWord = function(shouldHighlight) {
this.setOption("highlightSelectedWord", shouldHighlight);
};
this.getHighlightSelectedWord = function() {
return this.$highlightSelectedWord;
};
this.setAnimatedScroll = function(shouldAnimate){
this.renderer.setAnimatedScroll(shouldAnimate);
};
this.getAnimatedScroll = function(){
return this.renderer.getAnimatedScroll();
};
this.setShowInvisibles = function(showInvisibles) {
this.renderer.setShowInvisibles(showInvisibles);
};
this.getShowInvisibles = function() {
return this.renderer.getShowInvisibles();
};
this.setDisplayIndentGuides = function(display) {
this.renderer.setDisplayIndentGuides(display);
};
this.getDisplayIndentGuides = function() {
return this.renderer.getDisplayIndentGuides();
};
this.setShowPrintMargin = function(showPrintMargin) {
this.renderer.setShowPrintMargin(showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.renderer.getShowPrintMargin();
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.renderer.setPrintMarginColumn(showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.renderer.getPrintMarginColumn();
};
this.setReadOnly = function(readOnly) {
this.setOption("readOnly", readOnly);
};
this.getReadOnly = function() {
return this.getOption("readOnly");
};
this.setBehavioursEnabled = function (enabled) {
this.setOption("behavioursEnabled", enabled);
};
this.getBehavioursEnabled = function () {
return this.getOption("behavioursEnabled");
};
this.setWrapBehavioursEnabled = function (enabled) {
this.setOption("wrapBehavioursEnabled", enabled);
};
this.getWrapBehavioursEnabled = function () {
return this.getOption("wrapBehavioursEnabled");
};
this.setShowFoldWidgets = function(show) {
this.setOption("showFoldWidgets", show);
};
this.getShowFoldWidgets = function() {
return this.getOption("showFoldWidgets");
};
this.setFadeFoldWidgets = function(fade) {
this.setOption("fadeFoldWidgets", fade);
};
this.getFadeFoldWidgets = function() {
return this.getOption("fadeFoldWidgets");
};
this.remove = function(dir) {
if (this.selection.isEmpty()){
if (dir == "left")
this.selection.selectLeft();
else
this.selection.selectRight();
}
var range = this.getSelectionRange();
if (this.getBehavioursEnabled()) {
var session = this.session;
var state = session.getState(range.start.row);
var new_range = session.getMode().transformAction(state, 'deletion', this, session, range);
if (range.end.column === 0) {
var text = session.getTextRange(range);
if (text[text.length - 1] == "\n") {
var line = session.getLine(range.end.row);
if (/^\s+$/.test(line)) {
range.end.column = line.length;
}
}
}
if (new_range)
range = new_range;
}
this.session.remove(range);
this.clearSelection();
};
this.removeWordRight = function() {
if (this.selection.isEmpty())
this.selection.selectWordRight();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeWordLeft = function() {
if (this.selection.isEmpty())
this.selection.selectWordLeft();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineStart = function() {
if (this.selection.isEmpty())
this.selection.selectLineStart();
this.session.remove(this.getSelectionRange());
this.clearSelection();
};
this.removeToLineEnd = function() {
if (this.selection.isEmpty())
this.selection.selectLineEnd();
var range = this.getSelectionRange();
if (range.start.column == range.end.column && range.start.row == range.end.row) {
range.end.column = 0;
range.end.row++;
}
this.session.remove(range);
this.clearSelection();
};
this.splitLine = function() {
if (!this.selection.isEmpty()) {
this.session.remove(this.getSelectionRange());
this.clearSelection();
}
var cursor = this.getCursorPosition();
this.insert("\n");
this.moveCursorToPosition(cursor);
};
this.transposeLetters = function() {
if (!this.selection.isEmpty()) {
return;
}
var cursor = this.getCursorPosition();
var column = cursor.column;
if (column === 0)
return;
var line = this.session.getLine(cursor.row);
var swap, range;
if (column < line.length) {
swap = line.charAt(column) + line.charAt(column-1);
range = new Range(cursor.row, column-1, cursor.row, column+1);
}
else {
swap = line.charAt(column-1) + line.charAt(column-2);
range = new Range(cursor.row, column-2, cursor.row, column);
}
this.session.replace(range, swap);
};
this.toLowerCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toLowerCase());
this.selection.setSelectionRange(originalRange);
};
this.toUpperCase = function() {
var originalRange = this.getSelectionRange();
if (this.selection.isEmpty()) {
this.selection.selectWord();
}
var range = this.getSelectionRange();
var text = this.session.getTextRange(range);
this.session.replace(range, text.toUpperCase());
this.selection.setSelectionRange(originalRange);
};
this.indent = function() {
var session = this.session;
var range = this.getSelectionRange();
if (range.start.row < range.end.row) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
} else if (range.start.column < range.end.column) {
var text = session.getTextRange(range);
if (!/^\s+$/.test(text)) {
var rows = this.$getSelectedRows();
session.indentRows(rows.first, rows.last, "\t");
return;
}
}
var line = session.getLine(range.start.row);
var position = range.start;
var size = session.getTabSize();
var column = session.documentToScreenColumn(position.row, position.column);
if (this.session.getUseSoftTabs()) {
var count = (size - column % size);
var indentString = lang.stringRepeat(" ", count);
} else {
var count = column % size;
while (line[range.start.column - 1] == " " && count) {
range.start.column--;
count--;
}
this.selection.setSelectionRange(range);
indentString = "\t";
}
return this.insert(indentString);
};
this.blockIndent = function() {
var rows = this.$getSelectedRows();
this.session.indentRows(rows.first, rows.last, "\t");
};
this.blockOutdent = function() {
var selection = this.session.getSelection();
this.session.outdentRows(selection.getRange());
};
this.sortLines = function() {
var rows = this.$getSelectedRows();
var session = this.session;
var lines = [];
for (i = rows.first; i <= rows.last; i++)
lines.push(session.getLine(i));
lines.sort(function(a, b) {
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
return 0;
});
var deleteRange = new Range(0, 0, 0, 0);
for (var i = rows.first; i <= rows.last; i++) {
var line = session.getLine(i);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = line.length;
session.replace(deleteRange, lines[i-rows.first]);
}
};
this.toggleCommentLines = function() {
var state = this.session.getState(this.getCursorPosition().row);
var rows = this.$getSelectedRows();
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
};
this.toggleBlockComment = function() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
};
this.getNumberAt = function(row, column) {
var _numberRx = /[\-]?[0-9]+(?:\.[0-9]+)?/g;
_numberRx.lastIndex = 0;
var s = this.session.getLine(row);
while (_numberRx.lastIndex < column) {
var m = _numberRx.exec(s);
if(m.index <= column && m.index+m[0].length >= column){
var number = {
value: m[0],
start: m.index,
end: m.index+m[0].length
};
return number;
}
}
return null;
};
this.modifyNumber = function(amount) {
var row = this.selection.getCursor().row;
var column = this.selection.getCursor().column;
var charRange = new Range(row, column-1, row, column);
var c = this.session.getTextRange(charRange);
if (!isNaN(parseFloat(c)) && isFinite(c)) {
var nr = this.getNumberAt(row, column);
if (nr) {
var fp = nr.value.indexOf(".") >= 0 ? nr.start + nr.value.indexOf(".") + 1 : nr.end;
var decimals = nr.start + nr.value.length - fp;
var t = parseFloat(nr.value);
t *= Math.pow(10, decimals);
if(fp !== nr.end && column < fp){
amount *= Math.pow(10, nr.end - column - 1);
} else {
amount *= Math.pow(10, nr.end - column);
}
t += amount;
t /= Math.pow(10, decimals);
var nnr = t.toFixed(decimals);
var replaceRange = new Range(row, nr.start, row, nr.end);
this.session.replace(replaceRange, nnr);
this.moveCursorTo(row, Math.max(nr.start +1, column + nnr.length - nr.value.length));
}
}
};
this.removeLines = function() {
var rows = this.$getSelectedRows();
this.session.removeFullLines(rows.first, rows.last);
this.clearSelection();
};
this.duplicateSelection = function() {
var sel = this.selection;
var doc = this.session;
var range = sel.getRange();
var reverse = sel.isBackwards();
if (range.isEmpty()) {
var row = range.start.row;
doc.duplicateLines(row, row);
} else {
var point = reverse ? range.start : range.end;
var endPoint = doc.insert(point, doc.getTextRange(range), false);
range.start = point;
range.end = endPoint;
sel.setSelectionRange(range, reverse);
}
};
this.moveLinesDown = function() {
this.$moveLines(1, false);
};
this.moveLinesUp = function() {
this.$moveLines(-1, false);
};
this.moveText = function(range, toPosition, copy) {
return this.session.moveText(range, toPosition, copy);
};
this.copyLinesUp = function() {
this.$moveLines(-1, true);
};
this.copyLinesDown = function() {
this.$moveLines(1, true);
};
this.$moveLines = function(dir, copy) {
var rows, moved;
var selection = this.selection;
if (!selection.inMultiSelectMode || this.inVirtualSelectionMode) {
var range = selection.toOrientedRange();
rows = this.$getSelectedRows(range);
moved = this.session.$moveLines(rows.first, rows.last, copy ? 0 : dir);
if (copy && dir == -1) moved = 0;
range.moveBy(moved, 0);
selection.fromOrientedRange(range);
} else {
var ranges = selection.rangeList.ranges;
selection.rangeList.detach(this.session);
this.inVirtualSelectionMode = true;
var diff = 0;
var totalDiff = 0;
var l = ranges.length;
for (var i = 0; i < l; i++) {
var rangeIndex = i;
ranges[i].moveBy(diff, 0);
rows = this.$getSelectedRows(ranges[i]);
var first = rows.first;
var last = rows.last;
while (++i < l) {
if (totalDiff) ranges[i].moveBy(totalDiff, 0);
var subRows = this.$getSelectedRows(ranges[i]);
if (copy && subRows.first != last)
break;
else if (!copy && subRows.first > last + 1)
break;
last = subRows.last;
}
i--;
diff = this.session.$moveLines(first, last, copy ? 0 : dir);
if (copy && dir == -1) rangeIndex = i + 1;
while (rangeIndex <= i) {
ranges[rangeIndex].moveBy(diff, 0);
rangeIndex++;
}
if (!copy) diff = 0;
totalDiff += diff;
}
selection.fromOrientedRange(selection.ranges[0]);
selection.rangeList.attach(this.session);
this.inVirtualSelectionMode = false;
}
};
this.$getSelectedRows = function(range) {
range = (range || this.getSelectionRange()).collapseRows();
return {
first: this.session.getRowFoldStart(range.start.row),
last: this.session.getRowFoldEnd(range.end.row)
};
};
this.onCompositionStart = function(text) {
this.renderer.showComposition(this.getCursorPosition());
};
this.onCompositionUpdate = function(text) {
this.renderer.setCompositionText(text);
};
this.onCompositionEnd = function() {
this.renderer.hideComposition();
};
this.getFirstVisibleRow = function() {
return this.renderer.getFirstVisibleRow();
};
this.getLastVisibleRow = function() {
return this.renderer.getLastVisibleRow();
};
this.isRowVisible = function(row) {
return (row >= this.getFirstVisibleRow() && row <= this.getLastVisibleRow());
};
this.isRowFullyVisible = function(row) {
return (row >= this.renderer.getFirstFullyVisibleRow() && row <= this.renderer.getLastFullyVisibleRow());
};
this.$getVisibleRowCount = function() {
return this.renderer.getScrollBottomRow() - this.renderer.getScrollTopRow() + 1;
};
this.$moveByPage = function(dir, select) {
var renderer = this.renderer;
var config = this.renderer.layerConfig;
var rows = dir * Math.floor(config.height / config.lineHeight);
this.$blockScrolling++;
if (select === true) {
this.selection.$moveSelection(function(){
this.moveCursorBy(rows, 0);
});
} else if (select === false) {
this.selection.moveCursorBy(rows, 0);
this.selection.clearSelection();
}
this.$blockScrolling--;
var scrollTop = renderer.scrollTop;
renderer.scrollBy(0, rows * config.lineHeight);
if (select != null)
renderer.scrollCursorIntoView(null, 0.5);
renderer.animateScrolling(scrollTop);
};
this.selectPageDown = function() {
this.$moveByPage(1, true);
};
this.selectPageUp = function() {
this.$moveByPage(-1, true);
};
this.gotoPageDown = function() {
this.$moveByPage(1, false);
};
this.gotoPageUp = function() {
this.$moveByPage(-1, false);
};
this.scrollPageDown = function() {
this.$moveByPage(1);
};
this.scrollPageUp = function() {
this.$moveByPage(-1);
};
this.scrollToRow = function(row) {
this.renderer.scrollToRow(row);
};
this.scrollToLine = function(line, center, animate, callback) {
this.renderer.scrollToLine(line, center, animate, callback);
};
this.centerSelection = function() {
var range = this.getSelectionRange();
var pos = {
row: Math.floor(range.start.row + (range.end.row - range.start.row) / 2),
column: Math.floor(range.start.column + (range.end.column - range.start.column) / 2)
};
this.renderer.alignCursor(pos, 0.5);
};
this.getCursorPosition = function() {
return this.selection.getCursor();
};
this.getCursorPositionScreen = function() {
return this.session.documentToScreenPosition(this.getCursorPosition());
};
this.getSelectionRange = function() {
return this.selection.getRange();
};
this.selectAll = function() {
this.$blockScrolling += 1;
this.selection.selectAll();
this.$blockScrolling -= 1;
};
this.clearSelection = function() {
this.selection.clearSelection();
};
this.moveCursorTo = function(row, column) {
this.selection.moveCursorTo(row, column);
};
this.moveCursorToPosition = function(pos) {
this.selection.moveCursorToPosition(pos);
};
this.jumpToMatching = function(select, expand) {
var cursor = this.getCursorPosition();
var iterator = new TokenIterator(this.session, cursor.row, cursor.column);
var prevToken = iterator.getCurrentToken();
var token = prevToken || iterator.stepForward();
if (!token) return;
var matchType;
var found = false;
var depth = {};
var i = cursor.column - token.start;
var bracketType;
var brackets = {
")": "(",
"(": "(",
"]": "[",
"[": "[",
"{": "{",
"}": "{"
};
do {
if (token.value.match(/[{}()\[\]]/g)) {
for (; i < token.value.length && !found; i++) {
if (!brackets[token.value[i]]) {
continue;
}
bracketType = brackets[token.value[i]] + '.' + token.type.replace("rparen", "lparen");
if (isNaN(depth[bracketType])) {
depth[bracketType] = 0;
}
switch (token.value[i]) {
case '(':
case '[':
case '{':
depth[bracketType]++;
break;
case ')':
case ']':
case '}':
depth[bracketType]--;
if (depth[bracketType] === -1) {
matchType = 'bracket';
found = true;
}
break;
}
}
}
else if (token && token.type.indexOf('tag-name') !== -1) {
if (isNaN(depth[token.value])) {
depth[token.value] = 0;
}
if (prevToken.value === '<') {
depth[token.value]++;
}
else if (prevToken.value === '</') {
depth[token.value]--;
}
if (depth[token.value] === -1) {
matchType = 'tag';
found = true;
}
}
if (!found) {
prevToken = token;
token = iterator.stepForward();
i = 0;
}
} while (token && !found);
if (!matchType)
return;
var range, pos;
if (matchType === 'bracket') {
range = this.session.getBracketRange(cursor);
if (!range) {
range = new Range(
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() + i - 1,
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() + i - 1
);
pos = range.start;
if (expand || pos.row === cursor.row && Math.abs(pos.column - cursor.column) < 2)
range = this.session.getBracketRange(pos);
}
}
else if (matchType === 'tag') {
if (token && token.type.indexOf('tag-name') !== -1)
var tag = token.value;
else
return;
range = new Range(
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() - 2,
iterator.getCurrentTokenRow(),
iterator.getCurrentTokenColumn() - 2
);
if (range.compare(cursor.row, cursor.column) === 0) {
found = false;
do {
token = prevToken;
prevToken = iterator.stepBackward();
if (prevToken) {
if (prevToken.type.indexOf('tag-close') !== -1) {
range.setEnd(iterator.getCurrentTokenRow(), iterator.getCurrentTokenColumn() + 1);
}
if (token.value === tag && token.type.indexOf('tag-name') !== -1) {
if (prevToken.value === '<') {
depth[tag]++;
}
else if (prevToken.value === '</') {
depth[tag]--;
}
if (depth[tag] === 0)
found = true;
}
}
} while (prevToken && !found);
}
if (token && token.type.indexOf('tag-name')) {
pos = range.start;
if (pos.row == cursor.row && Math.abs(pos.column - cursor.column) < 2)
pos = range.end;
}
}
pos = range && range.cursor || pos;
if (pos) {
if (select) {
if (range && expand) {
this.selection.setRange(range);
} else if (range && range.isEqual(this.getSelectionRange())) {
this.clearSelection();
} else {
this.selection.selectTo(pos.row, pos.column);
}
} else {
this.selection.moveTo(pos.row, pos.column);
}
}
};
this.gotoLine = function(lineNumber, column, animate) {
this.selection.clearSelection();
this.session.unfold({row: lineNumber - 1, column: column || 0});
this.$blockScrolling += 1;
this.exitMultiSelectMode && this.exitMultiSelectMode();
this.moveCursorTo(lineNumber - 1, column || 0);
this.$blockScrolling -= 1;
if (!this.isRowFullyVisible(lineNumber - 1))
this.scrollToLine(lineNumber - 1, true, animate);
};
this.navigateTo = function(row, column) {
this.selection.moveTo(row, column);
};
this.navigateUp = function(times) {
if (this.selection.isMultiLine() && !this.selection.isBackwards()) {
var selectionStart = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionStart);
}
this.selection.clearSelection();
this.selection.moveCursorBy(-times || -1, 0);
};
this.navigateDown = function(times) {
if (this.selection.isMultiLine() && this.selection.isBackwards()) {
var selectionEnd = this.selection.anchor.getPosition();
return this.moveCursorToPosition(selectionEnd);
}
this.selection.clearSelection();
this.selection.moveCursorBy(times || 1, 0);
};
this.navigateLeft = function(times) {
if (!this.selection.isEmpty()) {
var selectionStart = this.getSelectionRange().start;
this.moveCursorToPosition(selectionStart);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorLeft();
}
}
this.clearSelection();
};
this.navigateRight = function(times) {
if (!this.selection.isEmpty()) {
var selectionEnd = this.getSelectionRange().end;
this.moveCursorToPosition(selectionEnd);
}
else {
times = times || 1;
while (times--) {
this.selection.moveCursorRight();
}
}
this.clearSelection();
};
this.navigateLineStart = function() {
this.selection.moveCursorLineStart();
this.clearSelection();
};
this.navigateLineEnd = function() {
this.selection.moveCursorLineEnd();
this.clearSelection();
};
this.navigateFileEnd = function() {
this.selection.moveCursorFileEnd();
this.clearSelection();
};
this.navigateFileStart = function() {
this.selection.moveCursorFileStart();
this.clearSelection();
};
this.navigateWordRight = function() {
this.selection.moveCursorWordRight();
this.clearSelection();
};
this.navigateWordLeft = function() {
this.selection.moveCursorWordLeft();
this.clearSelection();
};
this.replace = function(replacement, options) {
if (options)
this.$search.set(options);
var range = this.$search.find(this.session);
var replaced = 0;
if (!range)
return replaced;
if (this.$tryReplace(range, replacement)) {
replaced = 1;
}
if (range !== null) {
this.selection.setSelectionRange(range);
this.renderer.scrollSelectionIntoView(range.start, range.end);
}
return replaced;
};
this.replaceAll = function(replacement, options) {
if (options) {
this.$search.set(options);
}
var ranges = this.$search.findAll(this.session);
var replaced = 0;
if (!ranges.length)
return replaced;
this.$blockScrolling += 1;
var selection = this.getSelectionRange();
this.selection.moveTo(0, 0);
for (var i = ranges.length - 1; i >= 0; --i) {
if(this.$tryReplace(ranges[i], replacement)) {
replaced++;
}
}
this.selection.setSelectionRange(selection);
this.$blockScrolling -= 1;
return replaced;
};
this.$tryReplace = function(range, replacement) {
var input = this.session.getTextRange(range);
replacement = this.$search.replace(input, replacement);
if (replacement !== null) {
range.end = this.session.replace(range, replacement);
return range;
} else {
return null;
}
};
this.getLastSearchOptions = function() {
return this.$search.getOptions();
};
this.find = function(needle, options, animate) {
if (!options)
options = {};
if (typeof needle == "string" || needle instanceof RegExp)
options.needle = needle;
else if (typeof needle == "object")
oop.mixin(options, needle);
var range = this.selection.getRange();
if (options.needle == null) {
needle = this.session.getTextRange(range)
|| this.$search.$options.needle;
if (!needle) {
range = this.session.getWordRange(range.start.row, range.start.column);
needle = this.session.getTextRange(range);
}
this.$search.set({needle: needle});
}
this.$search.set(options);
if (!options.start)
this.$search.set({start: range});
var newRange = this.$search.find(this.session);
if (options.preventScroll)
return newRange;
if (newRange) {
this.revealRange(newRange, animate);
return newRange;
}
if (options.backwards)
range.start = range.end;
else
range.end = range.start;
this.selection.setRange(range);
};
this.findNext = function(options, animate) {
this.find({skipCurrent: true, backwards: false}, options, animate);
};
this.findPrevious = function(options, animate) {
this.find(options, {skipCurrent: true, backwards: true}, animate);
};
this.revealRange = function(range, animate) {
this.$blockScrolling += 1;
this.session.unfold(range);
this.selection.setSelectionRange(range);
this.$blockScrolling -= 1;
var scrollTop = this.renderer.scrollTop;
this.renderer.scrollSelectionIntoView(range.start, range.end, 0.5);
if (animate !== false)
this.renderer.animateScrolling(scrollTop);
};
this.undo = function() {
this.$blockScrolling++;
this.session.getUndoManager().undo();
this.$blockScrolling--;
this.renderer.scrollCursorIntoView(null, 0.5);
};
this.redo = function() {
this.$blockScrolling++;
this.session.getUndoManager().redo();
this.$blockScrolling--;
this.renderer.scrollCursorIntoView(null, 0.5);
};
this.destroy = function() {
this.renderer.destroy();
this._signal("destroy", this);
if (this.session) {
this.session.destroy();
}
};
this.setAutoScrollEditorIntoView = function(enable) {
if (!enable)
return;
var rect;
var self = this;
var shouldScroll = false;
if (!this.$scrollAnchor)
this.$scrollAnchor = document.createElement("div");
var scrollAnchor = this.$scrollAnchor;
scrollAnchor.style.cssText = "position:absolute";
this.container.insertBefore(scrollAnchor, this.container.firstChild);
var onChangeSelection = this.on("changeSelection", function() {
shouldScroll = true;
});
var onBeforeRender = this.renderer.on("beforeRender", function() {
if (shouldScroll)
rect = self.renderer.container.getBoundingClientRect();
});
var onAfterRender = this.renderer.on("afterRender", function() {
if (shouldScroll && rect && (self.isFocused()
|| self.searchBox && self.searchBox.isFocused())
) {
var renderer = self.renderer;
var pos = renderer.$cursorLayer.$pixelPos;
var config = renderer.layerConfig;
var top = pos.top - config.offset;
if (pos.top >= 0 && top + rect.top < 0) {
shouldScroll = true;
} else if (pos.top < config.height &&
pos.top + rect.top + config.lineHeight > window.innerHeight) {
shouldScroll = false;
} else {
shouldScroll = null;
}
if (shouldScroll != null) {
scrollAnchor.style.top = top + "px";
scrollAnchor.style.left = pos.left + "px";
scrollAnchor.style.height = config.lineHeight + "px";
scrollAnchor.scrollIntoView(shouldScroll);
}
shouldScroll = rect = null;
}
});
this.setAutoScrollEditorIntoView = function(enable) {
if (enable)
return;
delete this.setAutoScrollEditorIntoView;
this.off("changeSelection", onChangeSelection);
this.renderer.off("afterRender", onAfterRender);
this.renderer.off("beforeRender", onBeforeRender);
};
};
this.$resetCursorStyle = function() {
var style = this.$cursorStyle || "ace";
var cursorLayer = this.renderer.$cursorLayer;
if (!cursorLayer)
return;
cursorLayer.setSmoothBlinking(/smooth/.test(style));
cursorLayer.isBlinking = !this.$readOnly && style != "wide";
dom.setCssClass(cursorLayer.element, "ace_slim-cursors", /slim/.test(style));
};
}).call(Editor.prototype);
config.defineOptions(Editor.prototype, "editor", {
selectionStyle: {
set: function(style) {
this.onSelectionChange();
this._signal("changeSelectionStyle", {data: style});
},
initialValue: "line"
},
highlightActiveLine: {
set: function() {this.$updateHighlightActiveLine();},
initialValue: true
},
highlightSelectedWord: {
set: function(shouldHighlight) {this.$onSelectionChange();},
initialValue: true
},
readOnly: {
set: function(readOnly) {
this.$resetCursorStyle();
},
initialValue: false
},
cursorStyle: {
set: function(val) { this.$resetCursorStyle(); },
values: ["ace", "slim", "smooth", "wide"],
initialValue: "ace"
},
mergeUndoDeltas: {
values: [false, true, "always"],
initialValue: true
},
behavioursEnabled: {initialValue: true},
wrapBehavioursEnabled: {initialValue: true},
autoScrollEditorIntoView: {
set: function(val) {this.setAutoScrollEditorIntoView(val)}
},
keyboardHandler: {
set: function(val) { this.setKeyboardHandler(val); },
get: function() { return this.keybindingId; },
handlesSet: true
},
hScrollBarAlwaysVisible: "renderer",
vScrollBarAlwaysVisible: "renderer",
highlightGutterLine: "renderer",
animatedScroll: "renderer",
showInvisibles: "renderer",
showPrintMargin: "renderer",
printMarginColumn: "renderer",
printMargin: "renderer",
fadeFoldWidgets: "renderer",
showFoldWidgets: "renderer",
showLineNumbers: "renderer",
showGutter: "renderer",
displayIndentGuides: "renderer",
fontSize: "renderer",
fontFamily: "renderer",
maxLines: "renderer",
minLines: "renderer",
scrollPastEnd: "renderer",
fixedWidthGutter: "renderer",
theme: "renderer",
scrollSpeed: "$mouseHandler",
dragDelay: "$mouseHandler",
dragEnabled: "$mouseHandler",
focusTimout: "$mouseHandler",
tooltipFollowsMouse: "$mouseHandler",
firstLineNumber: "session",
overwrite: "session",
newLineMode: "session",
useWorker: "session",
useSoftTabs: "session",
tabSize: "session",
wrap: "session",
indentedSoftWrap: "session",
foldStyle: "session",
mode: "session"
});
exports.Editor = Editor;
});
ace.define("ace/undomanager",["require","exports","module"], function(acequire, exports, module) {
"use strict";
var UndoManager = function() {
this.reset();
};
(function() {
this.execute = function(options) {
var deltaSets = options.args[0];
this.$doc = options.args[1];
if (options.merge && this.hasUndo()){
this.dirtyCounter--;
deltaSets = this.$undoStack.pop().concat(deltaSets);
}
this.$undoStack.push(deltaSets);
this.$redoStack = [];
if (this.dirtyCounter < 0) {
this.dirtyCounter = NaN;
}
this.dirtyCounter++;
};
this.undo = function(dontSelect) {
var deltaSets = this.$undoStack.pop();
var undoSelectionRange = null;
if (deltaSets) {
undoSelectionRange = this.$doc.undoChanges(deltaSets, dontSelect);
this.$redoStack.push(deltaSets);
this.dirtyCounter--;
}
return undoSelectionRange;
};
this.redo = function(dontSelect) {
var deltaSets = this.$redoStack.pop();
var redoSelectionRange = null;
if (deltaSets) {
redoSelectionRange =
this.$doc.redoChanges(this.$deserializeDeltas(deltaSets), dontSelect);
this.$undoStack.push(deltaSets);
this.dirtyCounter++;
}
return redoSelectionRange;
};
this.reset = function() {
this.$undoStack = [];
this.$redoStack = [];
this.dirtyCounter = 0;
};
this.hasUndo = function() {
return this.$undoStack.length > 0;
};
this.hasRedo = function() {
return this.$redoStack.length > 0;
};
this.markClean = function() {
this.dirtyCounter = 0;
};
this.isClean = function() {
return this.dirtyCounter === 0;
};
this.$serializeDeltas = function(deltaSets) {
return cloneDeltaSetsObj(deltaSets, $serializeDelta);
};
this.$deserializeDeltas = function(deltaSets) {
return cloneDeltaSetsObj(deltaSets, $deserializeDelta);
};
function $serializeDelta(delta){
return {
action: delta.action,
start: delta.start,
end: delta.end,
lines: delta.lines.length == 1 ? null : delta.lines,
text: delta.lines.length == 1 ? delta.lines[0] : null
};
}
function $deserializeDelta(delta) {
return {
action: delta.action,
start: delta.start,
end: delta.end,
lines: delta.lines || [delta.text]
};
}
function cloneDeltaSetsObj(deltaSets_old, fnGetModifiedDelta) {
var deltaSets_new = new Array(deltaSets_old.length);
for (var i = 0; i < deltaSets_old.length; i++) {
var deltaSet_old = deltaSets_old[i];
var deltaSet_new = { group: deltaSet_old.group, deltas: new Array(deltaSet_old.length)};
for (var j = 0; j < deltaSet_old.deltas.length; j++) {
var delta_old = deltaSet_old.deltas[j];
deltaSet_new.deltas[j] = fnGetModifiedDelta(delta_old);
}
deltaSets_new[i] = deltaSet_new;
}
return deltaSets_new;
}
}).call(UndoManager.prototype);
exports.UndoManager = UndoManager;
});
ace.define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var oop = acequire("../lib/oop");
var lang = acequire("../lib/lang");
var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
var Gutter = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_gutter-layer";
parentEl.appendChild(this.element);
this.setShowFoldWidgets(this.$showFoldWidgets);
this.gutterWidth = 0;
this.$annotations = [];
this.$updateAnnotations = this.$updateAnnotations.bind(this);
this.$cells = [];
};
(function() {
oop.implement(this, EventEmitter);
this.setSession = function(session) {
if (this.session)
this.session.removeEventListener("change", this.$updateAnnotations);
this.session = session;
if (session)
session.on("change", this.$updateAnnotations);
};
this.addGutterDecoration = function(row, className){
if (window.console)
console.warn && console.warn("deprecated use session.addGutterDecoration");
this.session.addGutterDecoration(row, className);
};
this.removeGutterDecoration = function(row, className){
if (window.console)
console.warn && console.warn("deprecated use session.removeGutterDecoration");
this.session.removeGutterDecoration(row, className);
};
this.setAnnotations = function(annotations) {
this.$annotations = [];
for (var i = 0; i < annotations.length; i++) {
var annotation = annotations[i];
var row = annotation.row;
var rowInfo = this.$annotations[row];
if (!rowInfo)
rowInfo = this.$annotations[row] = {text: []};
var annoText = annotation.text;
annoText = annoText ? lang.escapeHTML(annoText) : annotation.html || "";
if (rowInfo.text.indexOf(annoText) === -1)
rowInfo.text.push(annoText);
var type = annotation.type;
if (type == "error")
rowInfo.className = " ace_error";
else if (type == "warning" && rowInfo.className != " ace_error")
rowInfo.className = " ace_warning";
else if (type == "info" && (!rowInfo.className))
rowInfo.className = " ace_info";
}
};
this.$updateAnnotations = function (delta) {
if (!this.$annotations.length)
return;
var firstRow = delta.start.row;
var len = delta.end.row - firstRow;
if (len === 0) {
} else if (delta.action == 'remove') {
this.$annotations.splice(firstRow, len + 1, null);
} else {
var args = new Array(len + 1);
args.unshift(firstRow, 1);
this.$annotations.splice.apply(this.$annotations, args);
}
};
this.update = function(config) {
var session = this.session;
var firstRow = config.firstRow;
var lastRow = Math.min(config.lastRow + config.gutterOffset, // needed to compensate for hor scollbar
session.getLength() - 1);
var fold = session.getNextFoldLine(firstRow);
var foldStart = fold ? fold.start.row : Infinity;
var foldWidgets = this.$showFoldWidgets && session.foldWidgets;
var breakpoints = session.$breakpoints;
var decorations = session.$decorations;
var firstLineNumber = session.$firstLineNumber;
var lastLineNumber = 0;
var gutterRenderer = session.gutterRenderer || this.$renderer;
var cell = null;
var index = -1;
var row = firstRow;
while (true) {
if (row > foldStart) {
row = fold.end.row + 1;
fold = session.getNextFoldLine(row, fold);
foldStart = fold ? fold.start.row : Infinity;
}
if (row > lastRow) {
while (this.$cells.length > index + 1) {
cell = this.$cells.pop();
this.element.removeChild(cell.element);
}
break;
}
cell = this.$cells[++index];
if (!cell) {
cell = {element: null, textNode: null, foldWidget: null};
cell.element = dom.createElement("div");
cell.textNode = document.createTextNode('');
cell.element.appendChild(cell.textNode);
this.element.appendChild(cell.element);
this.$cells[index] = cell;
}
var className = "ace_gutter-cell ";
if (breakpoints[row])
className += breakpoints[row];
if (decorations[row])
className += decorations[row];
if (this.$annotations[row])
className += this.$annotations[row].className;
if (cell.element.className != className)
cell.element.className = className;
var height = session.getRowLength(row) * config.lineHeight + "px";
if (height != cell.element.style.height)
cell.element.style.height = height;
if (foldWidgets) {
var c = foldWidgets[row];
if (c == null)
c = foldWidgets[row] = session.getFoldWidget(row);
}
if (c) {
if (!cell.foldWidget) {
cell.foldWidget = dom.createElement("span");
cell.element.appendChild(cell.foldWidget);
}
var className = "ace_fold-widget ace_" + c;
if (c == "start" && row == foldStart && row < fold.end.row)
className += " ace_closed";
else
className += " ace_open";
if (cell.foldWidget.className != className)
cell.foldWidget.className = className;
var height = config.lineHeight + "px";
if (cell.foldWidget.style.height != height)
cell.foldWidget.style.height = height;
} else {
if (cell.foldWidget) {
cell.element.removeChild(cell.foldWidget);
cell.foldWidget = null;
}
}
var text = lastLineNumber = gutterRenderer
? gutterRenderer.getText(session, row)
: row + firstLineNumber;
if (text != cell.textNode.data)
cell.textNode.data = text;
row++;
}
this.element.style.height = config.minHeight + "px";
if (this.$fixedWidth || session.$useWrapMode)
lastLineNumber = session.getLength() + firstLineNumber;
var gutterWidth = gutterRenderer
? gutterRenderer.getWidth(session, lastLineNumber, config)
: lastLineNumber.toString().length * config.characterWidth;
var padding = this.$padding || this.$computePadding();
gutterWidth += padding.left + padding.right;
if (gutterWidth !== this.gutterWidth && !isNaN(gutterWidth)) {
this.gutterWidth = gutterWidth;
this.element.style.width = Math.ceil(this.gutterWidth) + "px";
this._emit("changeGutterWidth", gutterWidth);
}
};
this.$fixedWidth = false;
this.$showLineNumbers = true;
this.$renderer = "";
this.setShowLineNumbers = function(show) {
this.$renderer = !show && {
getWidth: function() {return ""},
getText: function() {return ""}
};
};
this.getShowLineNumbers = function() {
return this.$showLineNumbers;
};
this.$showFoldWidgets = true;
this.setShowFoldWidgets = function(show) {
if (show)
dom.addCssClass(this.element, "ace_folding-enabled");
else
dom.removeCssClass(this.element, "ace_folding-enabled");
this.$showFoldWidgets = show;
this.$padding = null;
};
this.getShowFoldWidgets = function() {
return this.$showFoldWidgets;
};
this.$computePadding = function() {
if (!this.element.firstChild)
return {left: 0, right: 0};
var style = dom.computedStyle(this.element.firstChild);
this.$padding = {};
this.$padding.left = parseInt(style.paddingLeft) + 1 || 0;
this.$padding.right = parseInt(style.paddingRight) || 0;
return this.$padding;
};
this.getRegion = function(point) {
var padding = this.$padding || this.$computePadding();
var rect = this.element.getBoundingClientRect();
if (point.x < padding.left + rect.left)
return "markers";
if (this.$showFoldWidgets && point.x > rect.right - padding.right)
return "foldWidgets";
};
}).call(Gutter.prototype);
exports.Gutter = Gutter;
});
ace.define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
var dom = acequire("../lib/dom");
var Marker = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_marker-layer";
parentEl.appendChild(this.element);
};
(function() {
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setMarkers = function(markers) {
this.markers = markers;
};
this.update = function(config) {
var config = config || this.config;
if (!config)
return;
this.config = config;
var html = [];
for (var key in this.markers) {
var marker = this.markers[key];
if (!marker.range) {
marker.update(html, this, this.session, config);
continue;
}
var range = marker.range.clipRows(config.firstRow, config.lastRow);
if (range.isEmpty()) continue;
range = range.toScreenRange(this.session);
if (marker.renderer) {
var top = this.$getTop(range.start.row, config);
var left = this.$padding + range.start.column * config.characterWidth;
marker.renderer(html, range, left, top, config);
} else if (marker.type == "fullLine") {
this.drawFullLineMarker(html, range, marker.clazz, config);
} else if (marker.type == "screenLine") {
this.drawScreenLineMarker(html, range, marker.clazz, config);
} else if (range.isMultiLine()) {
if (marker.type == "text")
this.drawTextMarker(html, range, marker.clazz, config);
else
this.drawMultiLineMarker(html, range, marker.clazz, config);
} else {
this.drawSingleLineMarker(html, range, marker.clazz + " ace_start" + " ace_br15", config);
}
}
this.element.innerHTML = html.join("");
};
this.$getTop = function(row, layerConfig) {
return (row - layerConfig.firstRowScreen) * layerConfig.lineHeight;
};
function getBorderClass(tl, tr, br, bl) {
return (tl ? 1 : 0) | (tr ? 2 : 0) | (br ? 4 : 0) | (bl ? 8 : 0);
}
this.drawTextMarker = function(stringBuilder, range, clazz, layerConfig, extraStyle) {
var session = this.session;
var start = range.start.row;
var end = range.end.row;
var row = start;
var prev = 0;
var curr = 0;
var next = session.getScreenLastRowColumn(row);
var lineRange = new Range(row, range.start.column, row, curr);
for (; row <= end; row++) {
lineRange.start.row = lineRange.end.row = row;
lineRange.start.column = row == start ? range.start.column : session.getRowWrapIndent(row);
lineRange.end.column = next;
prev = curr;
curr = next;
next = row + 1 < end ? session.getScreenLastRowColumn(row + 1) : row == end ? 0 : range.end.column;
this.drawSingleLineMarker(stringBuilder, lineRange,
clazz + (row == start ? " ace_start" : "") + " ace_br"
+ getBorderClass(row == start || row == start + 1 && range.start.column, prev < curr, curr > next, row == end),
layerConfig, row == end ? 0 : 1, extraStyle);
}
};
this.drawMultiLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var padding = this.$padding;
var height = config.lineHeight;
var top = this.$getTop(range.start.row, config);
var left = padding + range.start.column * config.characterWidth;
extraStyle = extraStyle || "";
stringBuilder.push(
"<div class='", clazz, " ace_br1 ace_start' style='",
"height:", height, "px;",
"right:0;",
"top:", top, "px;",
"left:", left, "px;", extraStyle, "'></div>"
);
top = this.$getTop(range.end.row, config);
var width = range.end.column * config.characterWidth;
stringBuilder.push(
"<div class='", clazz, " ace_br12' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", padding, "px;", extraStyle, "'></div>"
);
height = (range.end.row - range.start.row - 1) * config.lineHeight;
if (height <= 0)
return;
top = this.$getTop(range.start.row + 1, config);
var radiusClass = (range.start.column ? 1 : 0) | (range.end.column ? 0 : 8);
stringBuilder.push(
"<div class='", clazz, (radiusClass ? " ace_br" + radiusClass : ""), "' style='",
"height:", height, "px;",
"right:0;",
"top:", top, "px;",
"left:", padding, "px;", extraStyle, "'></div>"
);
};
this.drawSingleLineMarker = function(stringBuilder, range, clazz, config, extraLength, extraStyle) {
var height = config.lineHeight;
var width = (range.end.column + (extraLength || 0) - range.start.column) * config.characterWidth;
var top = this.$getTop(range.start.row, config);
var left = this.$padding + range.start.column * config.characterWidth;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"width:", width, "px;",
"top:", top, "px;",
"left:", left, "px;", extraStyle || "", "'></div>"
);
};
this.drawFullLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var top = this.$getTop(range.start.row, config);
var height = config.lineHeight;
if (range.start.row != range.end.row)
height += this.$getTop(range.end.row, config) - top;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"top:", top, "px;",
"left:0;right:0;", extraStyle || "", "'></div>"
);
};
this.drawScreenLineMarker = function(stringBuilder, range, clazz, config, extraStyle) {
var top = this.$getTop(range.start.row, config);
var height = config.lineHeight;
stringBuilder.push(
"<div class='", clazz, "' style='",
"height:", height, "px;",
"top:", top, "px;",
"left:0;right:0;", extraStyle || "", "'></div>"
);
};
}).call(Marker.prototype);
exports.Marker = Marker;
});
ace.define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var dom = acequire("../lib/dom");
var lang = acequire("../lib/lang");
var useragent = acequire("../lib/useragent");
var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
var Text = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_text-layer";
parentEl.appendChild(this.element);
this.$updateEolChar = this.$updateEolChar.bind(this);
};
(function() {
oop.implement(this, EventEmitter);
this.EOF_CHAR = "\xB6";
this.EOL_CHAR_LF = "\xAC";
this.EOL_CHAR_CRLF = "\xa4";
this.EOL_CHAR = this.EOL_CHAR_LF;
this.TAB_CHAR = "\u2014"; //"\u21E5";
this.SPACE_CHAR = "\xB7";
this.$padding = 0;
this.$updateEolChar = function() {
var EOL_CHAR = this.session.doc.getNewLineCharacter() == "\n"
? this.EOL_CHAR_LF
: this.EOL_CHAR_CRLF;
if (this.EOL_CHAR != EOL_CHAR) {
this.EOL_CHAR = EOL_CHAR;
return true;
}
}
this.setPadding = function(padding) {
this.$padding = padding;
this.element.style.padding = "0 " + padding + "px";
};
this.getLineHeight = function() {
return this.$fontMetrics.$characterSize.height || 0;
};
this.getCharacterWidth = function() {
return this.$fontMetrics.$characterSize.width || 0;
};
this.$setFontMetrics = function(measure) {
this.$fontMetrics = measure;
this.$fontMetrics.on("changeCharacterSize", function(e) {
this._signal("changeCharacterSize", e);
}.bind(this));
this.$pollSizeChanges();
}
this.checkForSizeChanges = function() {
this.$fontMetrics.checkForSizeChanges();
};
this.$pollSizeChanges = function() {
return this.$pollSizeChangesTimer = this.$fontMetrics.$pollSizeChanges();
};
this.setSession = function(session) {
this.session = session;
if (session)
this.$computeTabString();
};
this.showInvisibles = false;
this.setShowInvisibles = function(showInvisibles) {
if (this.showInvisibles == showInvisibles)
return false;
this.showInvisibles = showInvisibles;
this.$computeTabString();
return true;
};
this.displayIndentGuides = true;
this.setDisplayIndentGuides = function(display) {
if (this.displayIndentGuides == display)
return false;
this.displayIndentGuides = display;
this.$computeTabString();
return true;
};
this.$tabStrings = [];
this.onChangeTabSize =
this.$computeTabString = function() {
var tabSize = this.session.getTabSize();
this.tabSize = tabSize;
var tabStr = this.$tabStrings = [0];
for (var i = 1; i < tabSize + 1; i++) {
if (this.showInvisibles) {
tabStr.push("<span class='ace_invisible ace_invisible_tab'>"
+ lang.stringRepeat(this.TAB_CHAR, i)
+ "</span>");
} else {
tabStr.push(lang.stringRepeat(" ", i));
}
}
if (this.displayIndentGuides) {
this.$indentGuideRe = /\s\S| \t|\t |\s$/;
var className = "ace_indent-guide";
var spaceClass = "";
var tabClass = "";
if (this.showInvisibles) {
className += " ace_invisible";
spaceClass = " ace_invisible_space";
tabClass = " ace_invisible_tab";
var spaceContent = lang.stringRepeat(this.SPACE_CHAR, this.tabSize);
var tabContent = lang.stringRepeat(this.TAB_CHAR, this.tabSize);
} else{
var spaceContent = lang.stringRepeat(" ", this.tabSize);
var tabContent = spaceContent;
}
this.$tabStrings[" "] = "<span class='" + className + spaceClass + "'>" + spaceContent + "</span>";
this.$tabStrings["\t"] = "<span class='" + className + tabClass + "'>" + tabContent + "</span>";
}
};
this.updateLines = function(config, firstRow, lastRow) {
if (this.config.lastRow != config.lastRow ||
this.config.firstRow != config.firstRow) {
this.scrollLines(config);
}
this.config = config;
var first = Math.max(firstRow, config.firstRow);
var last = Math.min(lastRow, config.lastRow);
var lineElements = this.element.childNodes;
var lineElementsIdx = 0;
for (var row = config.firstRow; row < first; row++) {
var foldLine = this.session.getFoldLine(row);
if (foldLine) {
if (foldLine.containsRow(first)) {
first = foldLine.start.row;
break;
} else {
row = foldLine.end.row;
}
}
lineElementsIdx ++;
}
var row = first;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row :Infinity;
}
if (row > last)
break;
var lineElement = lineElements[lineElementsIdx++];
if (lineElement) {
var html = [];
this.$renderLine(
html, row, !this.$useLineGroups(), row == foldStart ? foldLine : false
);
lineElement.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
lineElement.innerHTML = html.join("");
}
row++;
}
};
this.scrollLines = function(config) {
var oldConfig = this.config;
this.config = config;
if (!oldConfig || oldConfig.lastRow < config.firstRow)
return this.update(config);
if (config.lastRow < oldConfig.firstRow)
return this.update(config);
var el = this.element;
if (oldConfig.firstRow < config.firstRow)
for (var row=this.session.getFoldedRowCount(oldConfig.firstRow, config.firstRow - 1); row>0; row--)
el.removeChild(el.firstChild);
if (oldConfig.lastRow > config.lastRow)
for (var row=this.session.getFoldedRowCount(config.lastRow + 1, oldConfig.lastRow); row>0; row--)
el.removeChild(el.lastChild);
if (config.firstRow < oldConfig.firstRow) {
var fragment = this.$renderLinesFragment(config, config.firstRow, oldConfig.firstRow - 1);
if (el.firstChild)
el.insertBefore(fragment, el.firstChild);
else
el.appendChild(fragment);
}
if (config.lastRow > oldConfig.lastRow) {
var fragment = this.$renderLinesFragment(config, oldConfig.lastRow + 1, config.lastRow);
el.appendChild(fragment);
}
};
this.$renderLinesFragment = function(config, firstRow, lastRow) {
var fragment = this.element.ownerDocument.createDocumentFragment();
var row = firstRow;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row : Infinity;
}
if (row > lastRow)
break;
var container = dom.createElement("div");
var html = [];
this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
container.innerHTML = html.join("");
if (this.$useLineGroups()) {
container.className = 'ace_line_group';
fragment.appendChild(container);
container.style.height = config.lineHeight * this.session.getRowLength(row) + "px";
} else {
while(container.firstChild)
fragment.appendChild(container.firstChild);
}
row++;
}
return fragment;
};
this.update = function(config) {
this.config = config;
var html = [];
var firstRow = config.firstRow, lastRow = config.lastRow;
var row = firstRow;
var foldLine = this.session.getNextFoldLine(row);
var foldStart = foldLine ? foldLine.start.row : Infinity;
while (true) {
if (row > foldStart) {
row = foldLine.end.row+1;
foldLine = this.session.getNextFoldLine(row, foldLine);
foldStart = foldLine ? foldLine.start.row :Infinity;
}
if (row > lastRow)
break;
if (this.$useLineGroups())
html.push("<div class='ace_line_group' style='height:", config.lineHeight*this.session.getRowLength(row), "px'>")
this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
if (this.$useLineGroups())
html.push("</div>"); // end the line group
row++;
}
this.element.innerHTML = html.join("");
};
this.$textToken = {
"text": true,
"rparen": true,
"lparen": true
};
this.$renderToken = function(stringBuilder, screenColumn, token, value) {
var self = this;
var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g;
var replaceFunc = function(c, a, b, tabIdx, idx4) {
if (a) {
return self.showInvisibles
? "<span class='ace_invisible ace_invisible_space'>" + lang.stringRepeat(self.SPACE_CHAR, c.length) + "</span>"
: c;
} else if (c == "&") {
return "&#38;";
} else if (c == "<") {
return "&#60;";
} else if (c == ">") {
return "&#62;";
} else if (c == "\t") {
var tabSize = self.session.getScreenTabSize(screenColumn + tabIdx);
screenColumn += tabSize - 1;
return self.$tabStrings[tabSize];
} else if (c == "\u3000") {
var classToUse = self.showInvisibles ? "ace_cjk ace_invisible ace_invisible_space" : "ace_cjk";
var space = self.showInvisibles ? self.SPACE_CHAR : "";
screenColumn += 1;
return "<span class='" + classToUse + "' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + space + "</span>";
} else if (b) {
return "<span class='ace_invisible ace_invisible_space ace_invalid'>" + self.SPACE_CHAR + "</span>";
} else {
screenColumn += 1;
return "<span class='ace_cjk' style='width:" +
(self.config.characterWidth * 2) +
"px'>" + c + "</span>";
}
};
var output = value.replace(replaceReg, replaceFunc);
if (!this.$textToken[token.type]) {
var classes = "ace_" + token.type.replace(/\./g, " ace_");
var style = "";
if (token.type == "fold")
style = " style='width:" + (token.value.length * this.config.characterWidth) + "px;' ";
stringBuilder.push("<span class='", classes, "'", style, ">", output, "</span>");
}
else {
stringBuilder.push(output);
}
return screenColumn + value.length;
};
this.renderIndentGuide = function(stringBuilder, value, max) {
var cols = value.search(this.$indentGuideRe);
if (cols <= 0 || cols >= max)
return value;
if (value[0] == " ") {
cols -= cols % this.tabSize;
stringBuilder.push(lang.stringRepeat(this.$tabStrings[" "], cols/this.tabSize));
return value.substr(cols);
} else if (value[0] == "\t") {
stringBuilder.push(lang.stringRepeat(this.$tabStrings["\t"], cols));
return value.substr(cols);
}
return value;
};
this.$renderWrappedLine = function(stringBuilder, tokens, splits, onlyContents) {
var chars = 0;
var split = 0;
var splitChars = splits[0];
var screenColumn = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
var value = token.value;
if (i == 0 && this.displayIndentGuides) {
chars = value.length;
value = this.renderIndentGuide(stringBuilder, value, splitChars);
if (!value)
continue;
chars -= value.length;
}
if (chars + value.length < splitChars) {
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
chars += value.length;
} else {
while (chars + value.length >= splitChars) {
screenColumn = this.$renderToken(
stringBuilder, screenColumn,
token, value.substring(0, splitChars - chars)
);
value = value.substring(splitChars - chars);
chars = splitChars;
if (!onlyContents) {
stringBuilder.push("</div>",
"<div class='ace_line' style='height:",
this.config.lineHeight, "px'>"
);
}
stringBuilder.push(lang.stringRepeat("\xa0", splits.indent));
split ++;
screenColumn = 0;
splitChars = splits[split] || Number.MAX_VALUE;
}
if (value.length != 0) {
chars += value.length;
screenColumn = this.$renderToken(
stringBuilder, screenColumn, token, value
);
}
}
}
};
this.$renderSimpleLine = function(stringBuilder, tokens) {
var screenColumn = 0;
var token = tokens[0];
var value = token.value;
if (this.displayIndentGuides)
value = this.renderIndentGuide(stringBuilder, value);
if (value)
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
for (var i = 1; i < tokens.length; i++) {
token = tokens[i];
value = token.value;
screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
}
};
this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) {
if (!foldLine && foldLine != false)
foldLine = this.session.getFoldLine(row);
if (foldLine)
var tokens = this.$getFoldLineTokens(row, foldLine);
else
var tokens = this.session.getTokens(row);
if (!onlyContents) {
stringBuilder.push(
"<div class='ace_line' style='height:",
this.config.lineHeight * (
this.$useLineGroups() ? 1 :this.session.getRowLength(row)
), "px'>"
);
}
if (tokens.length) {
var splits = this.session.getRowSplitData(row);
if (splits && splits.length)
this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents);
else
this.$renderSimpleLine(stringBuilder, tokens);
}
if (this.showInvisibles) {
if (foldLine)
row = foldLine.end.row
stringBuilder.push(
"<span class='ace_invisible ace_invisible_eol'>",
row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR,
"</span>"
);
}
if (!onlyContents)
stringBuilder.push("</div>");
};
this.$getFoldLineTokens = function(row, foldLine) {
var session = this.session;
var renderTokens = [];
function addTokens(tokens, from, to) {
var idx = 0, col = 0;
while ((col + tokens[idx].value.length) < from) {
col += tokens[idx].value.length;
idx++;
if (idx == tokens.length)
return;
}
if (col != from) {
var value = tokens[idx].value.substring(from - col);
if (value.length > (to - from))
value = value.substring(0, to - from);
renderTokens.push({
type: tokens[idx].type,
value: value
});
col = from + value.length;
idx += 1;
}
while (col < to && idx < tokens.length) {
var value = tokens[idx].value;
if (value.length + col > to) {
renderTokens.push({
type: tokens[idx].type,
value: value.substring(0, to - col)
});
} else
renderTokens.push(tokens[idx]);
col += value.length;
idx += 1;
}
}
var tokens = session.getTokens(row);
foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
if (placeholder != null) {
renderTokens.push({
type: "fold",
value: placeholder
});
} else {
if (isNewRow)
tokens = session.getTokens(row);
if (tokens.length)
addTokens(tokens, lastColumn, column);
}
}, foldLine.end.row, this.session.getLine(foldLine.end.row).length);
return renderTokens;
};
this.$useLineGroups = function() {
return this.session.getUseWrapMode();
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.$measureNode)
this.$measureNode.parentNode.removeChild(this.$measureNode);
delete this.$measureNode;
};
}).call(Text.prototype);
exports.Text = Text;
});
ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var isIE8;
var Cursor = function(parentEl) {
this.element = dom.createElement("div");
this.element.className = "ace_layer ace_cursor-layer";
parentEl.appendChild(this.element);
if (isIE8 === undefined)
isIE8 = !("opacity" in this.element.style);
this.isVisible = false;
this.isBlinking = true;
this.blinkInterval = 1000;
this.smoothBlinking = false;
this.cursors = [];
this.cursor = this.addCursor();
dom.addCssClass(this.element, "ace_hidden-cursors");
this.$updateCursors = (isIE8
? this.$updateVisibility
: this.$updateOpacity).bind(this);
};
(function() {
this.$updateVisibility = function(val) {
var cursors = this.cursors;
for (var i = cursors.length; i--; )
cursors[i].style.visibility = val ? "" : "hidden";
};
this.$updateOpacity = function(val) {
var cursors = this.cursors;
for (var i = cursors.length; i--; )
cursors[i].style.opacity = val ? "" : "0";
};
this.$padding = 0;
this.setPadding = function(padding) {
this.$padding = padding;
};
this.setSession = function(session) {
this.session = session;
};
this.setBlinking = function(blinking) {
if (blinking != this.isBlinking){
this.isBlinking = blinking;
this.restartTimer();
}
};
this.setBlinkInterval = function(blinkInterval) {
if (blinkInterval != this.blinkInterval){
this.blinkInterval = blinkInterval;
this.restartTimer();
}
};
this.setSmoothBlinking = function(smoothBlinking) {
if (smoothBlinking != this.smoothBlinking && !isIE8) {
this.smoothBlinking = smoothBlinking;
dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking);
this.$updateCursors(true);
this.$updateCursors = (this.$updateOpacity).bind(this);
this.restartTimer();
}
};
this.addCursor = function() {
var el = dom.createElement("div");
el.className = "ace_cursor";
this.element.appendChild(el);
this.cursors.push(el);
return el;
};
this.removeCursor = function() {
if (this.cursors.length > 1) {
var el = this.cursors.pop();
el.parentNode.removeChild(el);
return el;
}
};
this.hideCursor = function() {
this.isVisible = false;
dom.addCssClass(this.element, "ace_hidden-cursors");
this.restartTimer();
};
this.showCursor = function() {
this.isVisible = true;
dom.removeCssClass(this.element, "ace_hidden-cursors");
this.restartTimer();
};
this.restartTimer = function() {
var update = this.$updateCursors;
clearInterval(this.intervalId);
clearTimeout(this.timeoutId);
if (this.smoothBlinking) {
dom.removeCssClass(this.element, "ace_smooth-blinking");
}
update(true);
if (!this.isBlinking || !this.blinkInterval || !this.isVisible)
return;
if (this.smoothBlinking) {
setTimeout(function(){
dom.addCssClass(this.element, "ace_smooth-blinking");
}.bind(this));
}
var blink = function(){
this.timeoutId = setTimeout(function() {
update(false);
}, 0.6 * this.blinkInterval);
}.bind(this);
this.intervalId = setInterval(function() {
update(true);
blink();
}, this.blinkInterval);
blink();
};
this.getPixelPosition = function(position, onScreen) {
if (!this.config || !this.session)
return {left : 0, top : 0};
if (!position)
position = this.session.selection.getCursor();
var pos = this.session.documentToScreenPosition(position);
var cursorLeft = this.$padding + pos.column * this.config.characterWidth;
var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
this.config.lineHeight;
return {left : cursorLeft, top : cursorTop};
};
this.update = function(config) {
this.config = config;
var selections = this.session.$selectionMarkers;
var i = 0, cursorIndex = 0;
if (selections === undefined || selections.length === 0){
selections = [{cursor: null}];
}
for (var i = 0, n = selections.length; i < n; i++) {
var pixelPos = this.getPixelPosition(selections[i].cursor, true);
if ((pixelPos.top > config.height + config.offset ||
pixelPos.top < 0) && i > 1) {
continue;
}
var style = (this.cursors[cursorIndex++] || this.addCursor()).style;
if (!this.drawCursor) {
style.left = pixelPos.left + "px";
style.top = pixelPos.top + "px";
style.width = config.characterWidth + "px";
style.height = config.lineHeight + "px";
} else {
this.drawCursor(style, pixelPos, config, selections[i], this.session);
}
}
while (this.cursors.length > cursorIndex)
this.removeCursor();
var overwrite = this.session.getOverwrite();
this.$setOverwrite(overwrite);
this.$pixelPos = pixelPos;
this.restartTimer();
};
this.drawCursor = null;
this.$setOverwrite = function(overwrite) {
if (overwrite != this.overwrite) {
this.overwrite = overwrite;
if (overwrite)
dom.addCssClass(this.element, "ace_overwrite-cursors");
else
dom.removeCssClass(this.element, "ace_overwrite-cursors");
}
};
this.destroy = function() {
clearInterval(this.intervalId);
clearTimeout(this.timeoutId);
};
}).call(Cursor.prototype);
exports.Cursor = Cursor;
});
ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var dom = acequire("./lib/dom");
var event = acequire("./lib/event");
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var MAX_SCROLL_H = 0x8000;
var ScrollBar = function(parent) {
this.element = dom.createElement("div");
this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix;
this.inner = dom.createElement("div");
this.inner.className = "ace_scrollbar-inner";
this.element.appendChild(this.inner);
parent.appendChild(this.element);
this.setVisible(false);
this.skipEvent = false;
event.addListener(this.element, "scroll", this.onScroll.bind(this));
event.addListener(this.element, "mousedown", event.preventDefault);
};
(function() {
oop.implement(this, EventEmitter);
this.setVisible = function(isVisible) {
this.element.style.display = isVisible ? "" : "none";
this.isVisible = isVisible;
this.coeff = 1;
};
}).call(ScrollBar.prototype);
var VScrollBar = function(parent, renderer) {
ScrollBar.call(this, parent);
this.scrollTop = 0;
this.scrollHeight = 0;
renderer.$scrollbarWidth =
this.width = dom.scrollbarWidth(parent.ownerDocument);
this.inner.style.width =
this.element.style.width = (this.width || 15) + 5 + "px";
};
oop.inherits(VScrollBar, ScrollBar);
(function() {
this.classSuffix = '-v';
this.onScroll = function() {
if (!this.skipEvent) {
this.scrollTop = this.element.scrollTop;
if (this.coeff != 1) {
var h = this.element.clientHeight / this.scrollHeight;
this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h);
}
this._emit("scroll", {data: this.scrollTop});
}
this.skipEvent = false;
};
this.getWidth = function() {
return this.isVisible ? this.width : 0;
};
this.setHeight = function(height) {
this.element.style.height = height + "px";
};
this.setInnerHeight =
this.setScrollHeight = function(height) {
this.scrollHeight = height;
if (height > MAX_SCROLL_H) {
this.coeff = MAX_SCROLL_H / height;
height = MAX_SCROLL_H;
} else if (this.coeff != 1) {
this.coeff = 1
}
this.inner.style.height = height + "px";
};
this.setScrollTop = function(scrollTop) {
if (this.scrollTop != scrollTop) {
this.skipEvent = true;
this.scrollTop = scrollTop;
this.element.scrollTop = scrollTop * this.coeff;
}
};
}).call(VScrollBar.prototype);
var HScrollBar = function(parent, renderer) {
ScrollBar.call(this, parent);
this.scrollLeft = 0;
this.height = renderer.$scrollbarWidth;
this.inner.style.height =
this.element.style.height = (this.height || 15) + 5 + "px";
};
oop.inherits(HScrollBar, ScrollBar);
(function() {
this.classSuffix = '-h';
this.onScroll = function() {
if (!this.skipEvent) {
this.scrollLeft = this.element.scrollLeft;
this._emit("scroll", {data: this.scrollLeft});
}
this.skipEvent = false;
};
this.getHeight = function() {
return this.isVisible ? this.height : 0;
};
this.setWidth = function(width) {
this.element.style.width = width + "px";
};
this.setInnerWidth = function(width) {
this.inner.style.width = width + "px";
};
this.setScrollWidth = function(width) {
this.inner.style.width = width + "px";
};
this.setScrollLeft = function(scrollLeft) {
if (this.scrollLeft != scrollLeft) {
this.skipEvent = true;
this.scrollLeft = this.element.scrollLeft = scrollLeft;
}
};
}).call(HScrollBar.prototype);
exports.ScrollBar = VScrollBar; // backward compatibility
exports.ScrollBarV = VScrollBar; // backward compatibility
exports.ScrollBarH = HScrollBar; // backward compatibility
exports.VScrollBar = VScrollBar;
exports.HScrollBar = HScrollBar;
});
ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) {
"use strict";
var event = acequire("./lib/event");
var RenderLoop = function(onRender, win) {
this.onRender = onRender;
this.pending = false;
this.changes = 0;
this.window = win || window;
};
(function() {
this.schedule = function(change) {
this.changes = this.changes | change;
if (!this.pending && this.changes) {
this.pending = true;
var _self = this;
event.nextFrame(function() {
_self.pending = false;
var changes;
while (changes = _self.changes) {
_self.changes = 0;
_self.onRender(changes);
}
}, this.window);
}
};
}).call(RenderLoop.prototype);
exports.RenderLoop = RenderLoop;
});
ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) {
var oop = acequire("../lib/oop");
var dom = acequire("../lib/dom");
var lang = acequire("../lib/lang");
var useragent = acequire("../lib/useragent");
var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
var CHAR_COUNT = 0;
var FontMetrics = exports.FontMetrics = function(parentEl) {
this.el = dom.createElement("div");
this.$setMeasureNodeStyles(this.el.style, true);
this.$main = dom.createElement("div");
this.$setMeasureNodeStyles(this.$main.style);
this.$measureNode = dom.createElement("div");
this.$setMeasureNodeStyles(this.$measureNode.style);
this.el.appendChild(this.$main);
this.el.appendChild(this.$measureNode);
parentEl.appendChild(this.el);
if (!CHAR_COUNT)
this.$testFractionalRect();
this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);
this.$characterSize = {width: 0, height: 0};
this.checkForSizeChanges();
};
(function() {
oop.implement(this, EventEmitter);
this.$characterSize = {width: 0, height: 0};
this.$testFractionalRect = function() {
var el = dom.createElement("div");
this.$setMeasureNodeStyles(el.style);
el.style.width = "0.2px";
document.documentElement.appendChild(el);
var w = el.getBoundingClientRect().width;
if (w > 0 && w < 1)
CHAR_COUNT = 50;
else
CHAR_COUNT = 100;
el.parentNode.removeChild(el);
};
this.$setMeasureNodeStyles = function(style, isRoot) {
style.width = style.height = "auto";
style.left = style.top = "0px";
style.visibility = "hidden";
style.position = "absolute";
style.whiteSpace = "pre";
if (useragent.isIE < 8) {
style["font-family"] = "inherit";
} else {
style.font = "inherit";
}
style.overflow = isRoot ? "hidden" : "visible";
};
this.checkForSizeChanges = function() {
var size = this.$measureSizes();
if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
this.$measureNode.style.fontWeight = "bold";
var boldSize = this.$measureSizes();
this.$measureNode.style.fontWeight = "";
this.$characterSize = size;
this.charSizes = Object.create(null);
this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
this._emit("changeCharacterSize", {data: size});
}
};
this.$pollSizeChanges = function() {
if (this.$pollSizeChangesTimer)
return this.$pollSizeChangesTimer;
var self = this;
return this.$pollSizeChangesTimer = setInterval(function() {
self.checkForSizeChanges();
}, 500);
};
this.setPolling = function(val) {
if (val) {
this.$pollSizeChanges();
} else if (this.$pollSizeChangesTimer) {
clearInterval(this.$pollSizeChangesTimer);
this.$pollSizeChangesTimer = 0;
}
};
this.$measureSizes = function() {
if (CHAR_COUNT === 50) {
var rect = null;
try {
rect = this.$measureNode.getBoundingClientRect();
} catch(e) {
rect = {width: 0, height:0 };
}
var size = {
height: rect.height,
width: rect.width / CHAR_COUNT
};
} else {
var size = {
height: this.$measureNode.clientHeight,
width: this.$measureNode.clientWidth / CHAR_COUNT
};
}
if (size.width === 0 || size.height === 0)
return null;
return size;
};
this.$measureCharWidth = function(ch) {
this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
var rect = this.$main.getBoundingClientRect();
return rect.width / CHAR_COUNT;
};
this.getCharacterWidth = function(ch) {
var w = this.charSizes[ch];
if (w === undefined) {
w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
}
return w;
};
this.destroy = function() {
clearInterval(this.$pollSizeChangesTimer);
if (this.el && this.el.parentNode)
this.el.parentNode.removeChild(this.el);
};
}).call(FontMetrics.prototype);
});
ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var dom = acequire("./lib/dom");
var config = acequire("./config");
var useragent = acequire("./lib/useragent");
var GutterLayer = acequire("./layer/gutter").Gutter;
var MarkerLayer = acequire("./layer/marker").Marker;
var TextLayer = acequire("./layer/text").Text;
var CursorLayer = acequire("./layer/cursor").Cursor;
var HScrollBar = acequire("./scrollbar").HScrollBar;
var VScrollBar = acequire("./scrollbar").VScrollBar;
var RenderLoop = acequire("./renderloop").RenderLoop;
var FontMetrics = acequire("./layer/font_metrics").FontMetrics;
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var editorCss = ".ace_editor {\
position: relative;\
overflow: hidden;\
font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\
direction: ltr;\
text-align: left;\
}\
.ace_scroller {\
position: absolute;\
overflow: hidden;\
top: 0;\
bottom: 0;\
background-color: inherit;\
-ms-user-select: none;\
-moz-user-select: none;\
-webkit-user-select: none;\
user-select: none;\
cursor: text;\
}\
.ace_content {\
position: absolute;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
min-width: 100%;\
}\
.ace_dragging .ace_scroller:before{\
position: absolute;\
top: 0;\
left: 0;\
right: 0;\
bottom: 0;\
content: '';\
background: rgba(250, 250, 250, 0.01);\
z-index: 1000;\
}\
.ace_dragging.ace_dark .ace_scroller:before{\
background: rgba(0, 0, 0, 0.01);\
}\
.ace_selecting, .ace_selecting * {\
cursor: text !important;\
}\
.ace_gutter {\
position: absolute;\
overflow : hidden;\
width: auto;\
top: 0;\
bottom: 0;\
left: 0;\
cursor: default;\
z-index: 4;\
-ms-user-select: none;\
-moz-user-select: none;\
-webkit-user-select: none;\
user-select: none;\
}\
.ace_gutter-active-line {\
position: absolute;\
left: 0;\
right: 0;\
}\
.ace_scroller.ace_scroll-left {\
box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\
}\
.ace_gutter-cell {\
padding-left: 19px;\
padding-right: 6px;\
background-repeat: no-repeat;\
}\
.ace_gutter-cell.ace_error {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\
background-repeat: no-repeat;\
background-position: 2px center;\
}\
.ace_gutter-cell.ace_warning {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\
background-position: 2px center;\
}\
.ace_gutter-cell.ace_info {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\
background-position: 2px center;\
}\
.ace_dark .ace_gutter-cell.ace_info {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\
}\
.ace_scrollbar {\
position: absolute;\
right: 0;\
bottom: 0;\
z-index: 6;\
}\
.ace_scrollbar-inner {\
position: absolute;\
cursor: text;\
left: 0;\
top: 0;\
}\
.ace_scrollbar-v{\
overflow-x: hidden;\
overflow-y: scroll;\
top: 0;\
}\
.ace_scrollbar-h {\
overflow-x: scroll;\
overflow-y: hidden;\
left: 0;\
}\
.ace_print-margin {\
position: absolute;\
height: 100%;\
}\
.ace_text-input {\
position: absolute;\
z-index: 0;\
width: 0.5em;\
height: 1em;\
opacity: 0;\
background: transparent;\
-moz-appearance: none;\
appearance: none;\
border: none;\
resize: none;\
outline: none;\
overflow: hidden;\
font: inherit;\
padding: 0 1px;\
margin: 0 -1px;\
text-indent: -1em;\
-ms-user-select: text;\
-moz-user-select: text;\
-webkit-user-select: text;\
user-select: text;\
white-space: pre!important;\
}\
.ace_text-input.ace_composition {\
background: inherit;\
color: inherit;\
z-index: 1000;\
opacity: 1;\
text-indent: 0;\
}\
.ace_layer {\
z-index: 1;\
position: absolute;\
overflow: hidden;\
word-wrap: normal;\
white-space: pre;\
height: 100%;\
width: 100%;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
pointer-events: none;\
}\
.ace_gutter-layer {\
position: relative;\
width: auto;\
text-align: right;\
pointer-events: auto;\
}\
.ace_text-layer {\
font: inherit !important;\
}\
.ace_cjk {\
display: inline-block;\
text-align: center;\
}\
.ace_cursor-layer {\
z-index: 4;\
}\
.ace_cursor {\
z-index: 4;\
position: absolute;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
border-left: 2px solid;\
transform: translatez(0);\
}\
.ace_slim-cursors .ace_cursor {\
border-left-width: 1px;\
}\
.ace_overwrite-cursors .ace_cursor {\
border-left-width: 0;\
border-bottom: 1px solid;\
}\
.ace_hidden-cursors .ace_cursor {\
opacity: 0.2;\
}\
.ace_smooth-blinking .ace_cursor {\
-webkit-transition: opacity 0.18s;\
transition: opacity 0.18s;\
}\
.ace_editor.ace_multiselect .ace_cursor {\
border-left-width: 1px;\
}\
.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\
position: absolute;\
z-index: 3;\
}\
.ace_marker-layer .ace_selection {\
position: absolute;\
z-index: 5;\
}\
.ace_marker-layer .ace_bracket {\
position: absolute;\
z-index: 6;\
}\
.ace_marker-layer .ace_active-line {\
position: absolute;\
z-index: 2;\
}\
.ace_marker-layer .ace_selected-word {\
position: absolute;\
z-index: 4;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
}\
.ace_line .ace_fold {\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
display: inline-block;\
height: 11px;\
margin-top: -2px;\
vertical-align: middle;\
background-image:\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\
background-repeat: no-repeat, repeat-x;\
background-position: center center, top left;\
color: transparent;\
border: 1px solid black;\
border-radius: 2px;\
cursor: pointer;\
pointer-events: auto;\
}\
.ace_dark .ace_fold {\
}\
.ace_fold:hover{\
background-image:\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\
}\
.ace_tooltip {\
background-color: #FFF;\
background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\
background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\
border: 1px solid gray;\
border-radius: 1px;\
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\
color: black;\
max-width: 100%;\
padding: 3px 4px;\
position: fixed;\
z-index: 999999;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
cursor: default;\
white-space: pre;\
word-wrap: break-word;\
line-height: normal;\
font-style: normal;\
font-weight: normal;\
letter-spacing: normal;\
pointer-events: none;\
}\
.ace_folding-enabled > .ace_gutter-cell {\
padding-right: 13px;\
}\
.ace_fold-widget {\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
margin: 0 -12px 0 1px;\
display: none;\
width: 11px;\
vertical-align: top;\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\
background-repeat: no-repeat;\
background-position: center;\
border-radius: 3px;\
border: 1px solid transparent;\
cursor: pointer;\
}\
.ace_folding-enabled .ace_fold-widget {\
display: inline-block; \
}\
.ace_fold-widget.ace_end {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\
}\
.ace_fold-widget.ace_closed {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\
}\
.ace_fold-widget:hover {\
border: 1px solid rgba(0, 0, 0, 0.3);\
background-color: rgba(255, 255, 255, 0.2);\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\
}\
.ace_fold-widget:active {\
border: 1px solid rgba(0, 0, 0, 0.4);\
background-color: rgba(0, 0, 0, 0.05);\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\
}\
.ace_dark .ace_fold-widget {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\
}\
.ace_dark .ace_fold-widget.ace_end {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\
}\
.ace_dark .ace_fold-widget.ace_closed {\
background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\
}\
.ace_dark .ace_fold-widget:hover {\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
background-color: rgba(255, 255, 255, 0.1);\
}\
.ace_dark .ace_fold-widget:active {\
box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
}\
.ace_fold-widget.ace_invalid {\
background-color: #FFB4B4;\
border-color: #DE5555;\
}\
.ace_fade-fold-widgets .ace_fold-widget {\
-webkit-transition: opacity 0.4s ease 0.05s;\
transition: opacity 0.4s ease 0.05s;\
opacity: 0;\
}\
.ace_fade-fold-widgets:hover .ace_fold-widget {\
-webkit-transition: opacity 0.05s ease 0.05s;\
transition: opacity 0.05s ease 0.05s;\
opacity:1;\
}\
.ace_underline {\
text-decoration: underline;\
}\
.ace_bold {\
font-weight: bold;\
}\
.ace_nobold .ace_bold {\
font-weight: normal;\
}\
.ace_italic {\
font-style: italic;\
}\
.ace_error-marker {\
background-color: rgba(255, 0, 0,0.2);\
position: absolute;\
z-index: 9;\
}\
.ace_highlight-marker {\
background-color: rgba(255, 255, 0,0.2);\
position: absolute;\
z-index: 8;\
}\
.ace_br1 {border-top-left-radius : 3px;}\
.ace_br2 {border-top-right-radius : 3px;}\
.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\
.ace_br4 {border-bottom-right-radius: 3px;}\
.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\
.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\
.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\
.ace_br8 {border-bottom-left-radius : 3px;}\
.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\
.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\
.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
";
dom.importCssString(editorCss, "ace_editor.css");
var VirtualRenderer = function(container, theme) {
var _self = this;
this.container = container || dom.createElement("div");
this.$keepTextAreaAtCursor = !useragent.isOldIE;
dom.addCssClass(this.container, "ace_editor");
this.setTheme(theme);
this.$gutter = dom.createElement("div");
this.$gutter.className = "ace_gutter";
this.container.appendChild(this.$gutter);
this.scroller = dom.createElement("div");
this.scroller.className = "ace_scroller";
this.container.appendChild(this.scroller);
this.content = dom.createElement("div");
this.content.className = "ace_content";
this.scroller.appendChild(this.content);
this.$gutterLayer = new GutterLayer(this.$gutter);
this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this));
this.$markerBack = new MarkerLayer(this.content);
var textLayer = this.$textLayer = new TextLayer(this.content);
this.canvas = textLayer.element;
this.$markerFront = new MarkerLayer(this.content);
this.$cursorLayer = new CursorLayer(this.content);
this.$horizScroll = false;
this.$vScroll = false;
this.scrollBar =
this.scrollBarV = new VScrollBar(this.container, this);
this.scrollBarH = new HScrollBar(this.container, this);
this.scrollBarV.addEventListener("scroll", function(e) {
if (!_self.$scrollAnimation)
_self.session.setScrollTop(e.data - _self.scrollMargin.top);
});
this.scrollBarH.addEventListener("scroll", function(e) {
if (!_self.$scrollAnimation)
_self.session.setScrollLeft(e.data - _self.scrollMargin.left);
});
this.scrollTop = 0;
this.scrollLeft = 0;
this.cursorPos = {
row : 0,
column : 0
};
this.$fontMetrics = new FontMetrics(this.container);
this.$textLayer.$setFontMetrics(this.$fontMetrics);
this.$textLayer.addEventListener("changeCharacterSize", function(e) {
_self.updateCharacterSize();
_self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height);
_self._signal("changeCharacterSize", e);
});
this.$size = {
width: 0,
height: 0,
scrollerHeight: 0,
scrollerWidth: 0,
$dirty: true
};
this.layerConfig = {
width : 1,
padding : 0,
firstRow : 0,
firstRowScreen: 0,
lastRow : 0,
lineHeight : 0,
characterWidth : 0,
minHeight : 1,
maxHeight : 1,
offset : 0,
height : 1,
gutterOffset: 1
};
this.scrollMargin = {
left: 0,
right: 0,
top: 0,
bottom: 0,
v: 0,
h: 0
};
this.$loop = new RenderLoop(
this.$renderChanges.bind(this),
this.container.ownerDocument.defaultView
);
this.$loop.schedule(this.CHANGE_FULL);
this.updateCharacterSize();
this.setPadding(4);
config.resetOptions(this);
config._emit("renderer", this);
};
(function() {
this.CHANGE_CURSOR = 1;
this.CHANGE_MARKER = 2;
this.CHANGE_GUTTER = 4;
this.CHANGE_SCROLL = 8;
this.CHANGE_LINES = 16;
this.CHANGE_TEXT = 32;
this.CHANGE_SIZE = 64;
this.CHANGE_MARKER_BACK = 128;
this.CHANGE_MARKER_FRONT = 256;
this.CHANGE_FULL = 512;
this.CHANGE_H_SCROLL = 1024;
oop.implement(this, EventEmitter);
this.updateCharacterSize = function() {
if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) {
this.$allowBoldFonts = this.$textLayer.allowBoldFonts;
this.setStyle("ace_nobold", !this.$allowBoldFonts);
}
this.layerConfig.characterWidth =
this.characterWidth = this.$textLayer.getCharacterWidth();
this.layerConfig.lineHeight =
this.lineHeight = this.$textLayer.getLineHeight();
this.$updatePrintMargin();
};
this.setSession = function(session) {
if (this.session)
this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode);
this.session = session;
if (session && this.scrollMargin.top && session.getScrollTop() <= 0)
session.setScrollTop(-this.scrollMargin.top);
this.$cursorLayer.setSession(session);
this.$markerBack.setSession(session);
this.$markerFront.setSession(session);
this.$gutterLayer.setSession(session);
this.$textLayer.setSession(session);
if (!session)
return;
this.$loop.schedule(this.CHANGE_FULL);
this.session.$setFontMetrics(this.$fontMetrics);
this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null;
this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this);
this.onChangeNewLineMode()
this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode);
};
this.updateLines = function(firstRow, lastRow, force) {
if (lastRow === undefined)
lastRow = Infinity;
if (!this.$changedLines) {
this.$changedLines = {
firstRow: firstRow,
lastRow: lastRow
};
}
else {
if (this.$changedLines.firstRow > firstRow)
this.$changedLines.firstRow = firstRow;
if (this.$changedLines.lastRow < lastRow)
this.$changedLines.lastRow = lastRow;
}
if (this.$changedLines.lastRow < this.layerConfig.firstRow) {
if (force)
this.$changedLines.lastRow = this.layerConfig.lastRow;
else
return;
}
if (this.$changedLines.firstRow > this.layerConfig.lastRow)
return;
this.$loop.schedule(this.CHANGE_LINES);
};
this.onChangeNewLineMode = function() {
this.$loop.schedule(this.CHANGE_TEXT);
this.$textLayer.$updateEolChar();
};
this.onChangeTabSize = function() {
this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER);
this.$textLayer.onChangeTabSize();
};
this.updateText = function() {
this.$loop.schedule(this.CHANGE_TEXT);
};
this.updateFull = function(force) {
if (force)
this.$renderChanges(this.CHANGE_FULL, true);
else
this.$loop.schedule(this.CHANGE_FULL);
};
this.updateFontSize = function() {
this.$textLayer.checkForSizeChanges();
};
this.$changes = 0;
this.$updateSizeAsync = function() {
if (this.$loop.pending)
this.$size.$dirty = true;
else
this.onResize();
};
this.onResize = function(force, gutterWidth, width, height) {
if (this.resizing > 2)
return;
else if (this.resizing > 0)
this.resizing++;
else
this.resizing = force ? 1 : 0;
var el = this.container;
if (!height)
height = el.clientHeight || el.scrollHeight;
if (!width)
width = el.clientWidth || el.scrollWidth;
var changes = this.$updateCachedSize(force, gutterWidth, width, height);
if (!this.$size.scrollerHeight || (!width && !height))
return this.resizing = 0;
if (force)
this.$gutterLayer.$padding = null;
if (force)
this.$renderChanges(changes | this.$changes, true);
else
this.$loop.schedule(changes | this.$changes);
if (this.resizing)
this.resizing = 0;
this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null;
};
this.$updateCachedSize = function(force, gutterWidth, width, height) {
height -= (this.$extraHeight || 0);
var changes = 0;
var size = this.$size;
var oldSize = {
width: size.width,
height: size.height,
scrollerHeight: size.scrollerHeight,
scrollerWidth: size.scrollerWidth
};
if (height && (force || size.height != height)) {
size.height = height;
changes |= this.CHANGE_SIZE;
size.scrollerHeight = size.height;
if (this.$horizScroll)
size.scrollerHeight -= this.scrollBarH.getHeight();
this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px";
changes = changes | this.CHANGE_SCROLL;
}
if (width && (force || size.width != width)) {
changes |= this.CHANGE_SIZE;
size.width = width;
if (gutterWidth == null)
gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
this.gutterWidth = gutterWidth;
this.scrollBarH.element.style.left =
this.scroller.style.left = gutterWidth + "px";
size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth());
this.scrollBarH.element.style.right =
this.scroller.style.right = this.scrollBarV.getWidth() + "px";
this.scroller.style.bottom = this.scrollBarH.getHeight() + "px";
if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
changes |= this.CHANGE_FULL;
}
size.$dirty = !width || !height;
if (changes)
this._signal("resize", oldSize);
return changes;
};
this.onGutterResize = function() {
var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
if (gutterWidth != this.gutterWidth)
this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height);
if (this.session.getUseWrapMode() && this.adjustWrapLimit()) {
this.$loop.schedule(this.CHANGE_FULL);
} else if (this.$size.$dirty) {
this.$loop.schedule(this.CHANGE_FULL);
} else {
this.$computeLayerConfig();
this.$loop.schedule(this.CHANGE_MARKER);
}
};
this.adjustWrapLimit = function() {
var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
var limit = Math.floor(availableWidth / this.characterWidth);
return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn);
};
this.setAnimatedScroll = function(shouldAnimate){
this.setOption("animatedScroll", shouldAnimate);
};
this.getAnimatedScroll = function() {
return this.$animatedScroll;
};
this.setShowInvisibles = function(showInvisibles) {
this.setOption("showInvisibles", showInvisibles);
};
this.getShowInvisibles = function() {
return this.getOption("showInvisibles");
};
this.getDisplayIndentGuides = function() {
return this.getOption("displayIndentGuides");
};
this.setDisplayIndentGuides = function(display) {
this.setOption("displayIndentGuides", display);
};
this.setShowPrintMargin = function(showPrintMargin) {
this.setOption("showPrintMargin", showPrintMargin);
};
this.getShowPrintMargin = function() {
return this.getOption("showPrintMargin");
};
this.setPrintMarginColumn = function(showPrintMargin) {
this.setOption("printMarginColumn", showPrintMargin);
};
this.getPrintMarginColumn = function() {
return this.getOption("printMarginColumn");
};
this.getShowGutter = function(){
return this.getOption("showGutter");
};
this.setShowGutter = function(show){
return this.setOption("showGutter", show);
};
this.getFadeFoldWidgets = function(){
return this.getOption("fadeFoldWidgets")
};
this.setFadeFoldWidgets = function(show) {
this.setOption("fadeFoldWidgets", show);
};
this.setHighlightGutterLine = function(shouldHighlight) {
this.setOption("highlightGutterLine", shouldHighlight);
};
this.getHighlightGutterLine = function() {
return this.getOption("highlightGutterLine");
};
this.$updateGutterLineHighlight = function() {
var pos = this.$cursorLayer.$pixelPos;
var height = this.layerConfig.lineHeight;
if (this.session.getUseWrapMode()) {
var cursor = this.session.selection.getCursor();
cursor.column = 0;
pos = this.$cursorLayer.getPixelPosition(cursor, true);
height *= this.session.getRowLength(cursor.row);
}
this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px";
this.$gutterLineHighlight.style.height = height + "px";
};
this.$updatePrintMargin = function() {
if (!this.$showPrintMargin && !this.$printMarginEl)
return;
if (!this.$printMarginEl) {
var containerEl = dom.createElement("div");
containerEl.className = "ace_layer ace_print-margin-layer";
this.$printMarginEl = dom.createElement("div");
this.$printMarginEl.className = "ace_print-margin";
containerEl.appendChild(this.$printMarginEl);
this.content.insertBefore(containerEl, this.content.firstChild);
}
var style = this.$printMarginEl.style;
style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px";
style.visibility = this.$showPrintMargin ? "visible" : "hidden";
if (this.session && this.session.$wrap == -1)
this.adjustWrapLimit();
};
this.getContainerElement = function() {
return this.container;
};
this.getMouseEventTarget = function() {
return this.scroller;
};
this.getTextAreaContainer = function() {
return this.container;
};
this.$moveTextAreaToCursor = function() {
if (!this.$keepTextAreaAtCursor)
return;
var config = this.layerConfig;
var posTop = this.$cursorLayer.$pixelPos.top;
var posLeft = this.$cursorLayer.$pixelPos.left;
posTop -= config.offset;
var style = this.textarea.style;
var h = this.lineHeight;
if (posTop < 0 || posTop > config.height - h) {
style.top = style.left = "0";
return;
}
var w = this.characterWidth;
if (this.$composition) {
var val = this.textarea.value.replace(/^\x01+/, "");
w *= (this.session.$getStringScreenWidth(val)[0]+2);
h += 2;
}
posLeft -= this.scrollLeft;
if (posLeft > this.$size.scrollerWidth - w)
posLeft = this.$size.scrollerWidth - w;
posLeft += this.gutterWidth;
style.height = h + "px";
style.width = w + "px";
style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px";
style.top = Math.min(posTop, this.$size.height - h) + "px";
};
this.getFirstVisibleRow = function() {
return this.layerConfig.firstRow;
};
this.getFirstFullyVisibleRow = function() {
return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
};
this.getLastFullyVisibleRow = function() {
var config = this.layerConfig;
var lastRow = config.lastRow
var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight;
if (top - this.session.getScrollTop() > config.height - config.lineHeight)
return lastRow - 1;
return lastRow;
};
this.getLastVisibleRow = function() {
return this.layerConfig.lastRow;
};
this.$padding = null;
this.setPadding = function(padding) {
this.$padding = padding;
this.$textLayer.setPadding(padding);
this.$cursorLayer.setPadding(padding);
this.$markerFront.setPadding(padding);
this.$markerBack.setPadding(padding);
this.$loop.schedule(this.CHANGE_FULL);
this.$updatePrintMargin();
};
this.setScrollMargin = function(top, bottom, left, right) {
var sm = this.scrollMargin;
sm.top = top|0;
sm.bottom = bottom|0;
sm.right = right|0;
sm.left = left|0;
sm.v = sm.top + sm.bottom;
sm.h = sm.left + sm.right;
if (sm.top && this.scrollTop <= 0 && this.session)
this.session.setScrollTop(-sm.top);
this.updateFull();
};
this.getHScrollBarAlwaysVisible = function() {
return this.$hScrollBarAlwaysVisible;
};
this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
this.setOption("hScrollBarAlwaysVisible", alwaysVisible);
};
this.getVScrollBarAlwaysVisible = function() {
return this.$vScrollBarAlwaysVisible;
};
this.setVScrollBarAlwaysVisible = function(alwaysVisible) {
this.setOption("vScrollBarAlwaysVisible", alwaysVisible);
};
this.$updateScrollBarV = function() {
var scrollHeight = this.layerConfig.maxHeight;
var scrollerHeight = this.$size.scrollerHeight;
if (!this.$maxLines && this.$scrollPastEnd) {
scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd;
if (this.scrollTop > scrollHeight - scrollerHeight) {
scrollHeight = this.scrollTop + scrollerHeight;
this.scrollBarV.scrollTop = null;
}
}
this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v);
this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top);
};
this.$updateScrollBarH = function() {
this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h);
this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left);
};
this.$frozen = false;
this.freeze = function() {
this.$frozen = true;
};
this.unfreeze = function() {
this.$frozen = false;
};
this.$renderChanges = function(changes, force) {
if (this.$changes) {
changes |= this.$changes;
this.$changes = 0;
}
if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) {
this.$changes |= changes;
return;
}
if (this.$size.$dirty) {
this.$changes |= changes;
return this.onResize(true);
}
if (!this.lineHeight) {
this.$textLayer.checkForSizeChanges();
}
this._signal("beforeRender");
var config = this.layerConfig;
if (changes & this.CHANGE_FULL ||
changes & this.CHANGE_SIZE ||
changes & this.CHANGE_TEXT ||
changes & this.CHANGE_LINES ||
changes & this.CHANGE_SCROLL ||
changes & this.CHANGE_H_SCROLL
) {
changes |= this.$computeLayerConfig();
if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) {
var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight;
if (st > 0) {
this.scrollTop = st;
changes = changes | this.CHANGE_SCROLL;
changes |= this.$computeLayerConfig();
}
}
config = this.layerConfig;
this.$updateScrollBarV();
if (changes & this.CHANGE_H_SCROLL)
this.$updateScrollBarH();
this.$gutterLayer.element.style.marginTop = (-config.offset) + "px";
this.content.style.marginTop = (-config.offset) + "px";
this.content.style.width = config.width + 2 * this.$padding + "px";
this.content.style.height = config.minHeight + "px";
}
if (changes & this.CHANGE_H_SCROLL) {
this.content.style.marginLeft = -this.scrollLeft + "px";
this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left";
}
if (changes & this.CHANGE_FULL) {
this.$textLayer.update(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
this.$markerBack.update(config);
this.$markerFront.update(config);
this.$cursorLayer.update(config);
this.$moveTextAreaToCursor();
this.$highlightGutterLine && this.$updateGutterLineHighlight();
this._signal("afterRender");
return;
}
if (changes & this.CHANGE_SCROLL) {
if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
this.$textLayer.update(config);
else
this.$textLayer.scrollLines(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
this.$markerBack.update(config);
this.$markerFront.update(config);
this.$cursorLayer.update(config);
this.$highlightGutterLine && this.$updateGutterLineHighlight();
this.$moveTextAreaToCursor();
this._signal("afterRender");
return;
}
if (changes & this.CHANGE_TEXT) {
this.$textLayer.update(config);
if (this.$showGutter)
this.$gutterLayer.update(config);
}
else if (changes & this.CHANGE_LINES) {
if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter)
this.$gutterLayer.update(config);
}
else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) {
if (this.$showGutter)
this.$gutterLayer.update(config);
}
if (changes & this.CHANGE_CURSOR) {
this.$cursorLayer.update(config);
this.$moveTextAreaToCursor();
this.$highlightGutterLine && this.$updateGutterLineHighlight();
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
this.$markerFront.update(config);
}
if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
this.$markerBack.update(config);
}
this._signal("afterRender");
};
this.$autosize = function() {
var height = this.session.getScreenLength() * this.lineHeight;
var maxHeight = this.$maxLines * this.lineHeight;
var desiredHeight = Math.min(maxHeight,
Math.max((this.$minLines || 1) * this.lineHeight, height)
) + this.scrollMargin.v + (this.$extraHeight || 0);
if (this.$horizScroll)
desiredHeight += this.scrollBarH.getHeight();
if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight)
desiredHeight = this.$maxPixelHeight;
var vScroll = height > maxHeight;
if (desiredHeight != this.desiredHeight ||
this.$size.height != this.desiredHeight || vScroll != this.$vScroll) {
if (vScroll != this.$vScroll) {
this.$vScroll = vScroll;
this.scrollBarV.setVisible(vScroll);
}
var w = this.container.clientWidth;
this.container.style.height = desiredHeight + "px";
this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight);
this.desiredHeight = desiredHeight;
this._signal("autosize");
}
};
this.$computeLayerConfig = function() {
var session = this.session;
var size = this.$size;
var hideScrollbars = size.height <= 2 * this.lineHeight;
var screenLines = this.session.getScreenLength();
var maxHeight = screenLines * this.lineHeight;
var longestLine = this.$getLongestLine();
var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible ||
size.scrollerWidth - longestLine - 2 * this.$padding < 0);
var hScrollChanged = this.$horizScroll !== horizScroll;
if (hScrollChanged) {
this.$horizScroll = horizScroll;
this.scrollBarH.setVisible(horizScroll);
}
var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine
if (this.$maxLines && this.lineHeight > 1)
this.$autosize();
var offset = this.scrollTop % this.lineHeight;
var minHeight = size.scrollerHeight + this.lineHeight;
var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd
? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd
: 0;
maxHeight += scrollPastEnd;
var sm = this.scrollMargin;
this.session.setScrollTop(Math.max(-sm.top,
Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom)));
this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft,
longestLine + 2 * this.$padding - size.scrollerWidth + sm.right)));
var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible ||
size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top);
var vScrollChanged = vScrollBefore !== vScroll;
if (vScrollChanged) {
this.$vScroll = vScroll;
this.scrollBarV.setVisible(vScroll);
}
var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
var lastRow = firstRow + lineCount;
var firstRowScreen, firstRowHeight;
var lineHeight = this.lineHeight;
firstRow = session.screenToDocumentRow(firstRow, 0);
var foldLine = session.getFoldLine(firstRow);
if (foldLine) {
firstRow = foldLine.start.row;
}
firstRowScreen = session.documentToScreenRow(firstRow, 0);
firstRowHeight = session.getRowLength(firstRow) * lineHeight;
lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight +
firstRowHeight;
offset = this.scrollTop - firstRowScreen * lineHeight;
var changes = 0;
if (this.layerConfig.width != longestLine)
changes = this.CHANGE_H_SCROLL;
if (hScrollChanged || vScrollChanged) {
changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height);
this._signal("scrollbarVisibilityChanged");
if (vScrollChanged)
longestLine = this.$getLongestLine();
}
this.layerConfig = {
width : longestLine,
padding : this.$padding,
firstRow : firstRow,
firstRowScreen: firstRowScreen,
lastRow : lastRow,
lineHeight : lineHeight,
characterWidth : this.characterWidth,
minHeight : minHeight,
maxHeight : maxHeight,
offset : offset,
gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0,
height : this.$size.scrollerHeight
};
return changes;
};
this.$updateLines = function() {
var firstRow = this.$changedLines.firstRow;
var lastRow = this.$changedLines.lastRow;
this.$changedLines = null;
var layerConfig = this.layerConfig;
if (firstRow > layerConfig.lastRow + 1) { return; }
if (lastRow < layerConfig.firstRow) { return; }
if (lastRow === Infinity) {
if (this.$showGutter)
this.$gutterLayer.update(layerConfig);
this.$textLayer.update(layerConfig);
return;
}
this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
return true;
};
this.$getLongestLine = function() {
var charCount = this.session.getScreenWidth();
if (this.showInvisibles && !this.session.$useWrapMode)
charCount += 1;
return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth));
};
this.updateFrontMarkers = function() {
this.$markerFront.setMarkers(this.session.getMarkers(true));
this.$loop.schedule(this.CHANGE_MARKER_FRONT);
};
this.updateBackMarkers = function() {
this.$markerBack.setMarkers(this.session.getMarkers());
this.$loop.schedule(this.CHANGE_MARKER_BACK);
};
this.addGutterDecoration = function(row, className){
this.$gutterLayer.addGutterDecoration(row, className);
};
this.removeGutterDecoration = function(row, className){
this.$gutterLayer.removeGutterDecoration(row, className);
};
this.updateBreakpoints = function(rows) {
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.setAnnotations = function(annotations) {
this.$gutterLayer.setAnnotations(annotations);
this.$loop.schedule(this.CHANGE_GUTTER);
};
this.updateCursor = function() {
this.$loop.schedule(this.CHANGE_CURSOR);
};
this.hideCursor = function() {
this.$cursorLayer.hideCursor();
};
this.showCursor = function() {
this.$cursorLayer.showCursor();
};
this.scrollSelectionIntoView = function(anchor, lead, offset) {
this.scrollCursorIntoView(anchor, offset);
this.scrollCursorIntoView(lead, offset);
};
this.scrollCursorIntoView = function(cursor, offset, $viewMargin) {
if (this.$size.scrollerHeight === 0)
return;
var pos = this.$cursorLayer.getPixelPosition(cursor);
var left = pos.left;
var top = pos.top;
var topMargin = $viewMargin && $viewMargin.top || 0;
var bottomMargin = $viewMargin && $viewMargin.bottom || 0;
var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop;
if (scrollTop + topMargin > top) {
if (offset && scrollTop + topMargin > top + this.lineHeight)
top -= offset * this.$size.scrollerHeight;
if (top === 0)
top = -this.scrollMargin.top;
this.session.setScrollTop(top);
} else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) {
if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight)
top += offset * this.$size.scrollerHeight;
this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight);
}
var scrollLeft = this.scrollLeft;
if (scrollLeft > left) {
if (left < this.$padding + 2 * this.layerConfig.characterWidth)
left = -this.scrollMargin.left;
this.session.setScrollLeft(left);
} else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
} else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) {
this.session.setScrollLeft(0);
}
};
this.getScrollTop = function() {
return this.session.getScrollTop();
};
this.getScrollLeft = function() {
return this.session.getScrollLeft();
};
this.getScrollTopRow = function() {
return this.scrollTop / this.lineHeight;
};
this.getScrollBottomRow = function() {
return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
};
this.scrollToRow = function(row) {
this.session.setScrollTop(row * this.lineHeight);
};
this.alignCursor = function(cursor, alignment) {
if (typeof cursor == "number")
cursor = {row: cursor, column: 0};
var pos = this.$cursorLayer.getPixelPosition(cursor);
var h = this.$size.scrollerHeight - this.lineHeight;
var offset = pos.top - h * (alignment || 0);
this.session.setScrollTop(offset);
return offset;
};
this.STEPS = 8;
this.$calcSteps = function(fromValue, toValue){
var i = 0;
var l = this.STEPS;
var steps = [];
var func = function(t, x_min, dx) {
return dx * (Math.pow(t - 1, 3) + 1) + x_min;
};
for (i = 0; i < l; ++i)
steps.push(func(i / this.STEPS, fromValue, toValue - fromValue));
return steps;
};
this.scrollToLine = function(line, center, animate, callback) {
var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0});
var offset = pos.top;
if (center)
offset -= this.$size.scrollerHeight / 2;
var initialScroll = this.scrollTop;
this.session.setScrollTop(offset);
if (animate !== false)
this.animateScrolling(initialScroll, callback);
};
this.animateScrolling = function(fromValue, callback) {
var toValue = this.scrollTop;
if (!this.$animatedScroll)
return;
var _self = this;
if (fromValue == toValue)
return;
if (this.$scrollAnimation) {
var oldSteps = this.$scrollAnimation.steps;
if (oldSteps.length) {
fromValue = oldSteps[0];
if (fromValue == toValue)
return;
}
}
var steps = _self.$calcSteps(fromValue, toValue);
this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps};
clearInterval(this.$timer);
_self.session.setScrollTop(steps.shift());
_self.session.$scrollTop = toValue;
this.$timer = setInterval(function() {
if (steps.length) {
_self.session.setScrollTop(steps.shift());
_self.session.$scrollTop = toValue;
} else if (toValue != null) {
_self.session.$scrollTop = -1;
_self.session.setScrollTop(toValue);
toValue = null;
} else {
_self.$timer = clearInterval(_self.$timer);
_self.$scrollAnimation = null;
callback && callback();
}
}, 10);
};
this.scrollToY = function(scrollTop) {
if (this.scrollTop !== scrollTop) {
this.$loop.schedule(this.CHANGE_SCROLL);
this.scrollTop = scrollTop;
}
};
this.scrollToX = function(scrollLeft) {
if (this.scrollLeft !== scrollLeft)
this.scrollLeft = scrollLeft;
this.$loop.schedule(this.CHANGE_H_SCROLL);
};
this.scrollTo = function(x, y) {
this.session.setScrollTop(y);
this.session.setScrollLeft(y);
};
this.scrollBy = function(deltaX, deltaY) {
deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY);
deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX);
};
this.isScrollableBy = function(deltaX, deltaY) {
if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top)
return true;
if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight
- this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom)
return true;
if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left)
return true;
if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth
- this.layerConfig.width < -1 + this.scrollMargin.right)
return true;
};
this.pixelToScreenCoordinates = function(x, y) {
var canvasPos = this.scroller.getBoundingClientRect();
var offset = (x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth;
var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight);
var col = Math.round(offset);
return {row: row, column: col, side: offset - col > 0 ? 1 : -1};
};
this.screenToTextCoordinates = function(x, y) {
var canvasPos = this.scroller.getBoundingClientRect();
var col = Math.round(
(x + this.scrollLeft - canvasPos.left - this.$padding) / this.characterWidth
);
var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight;
return this.session.screenToDocumentPosition(row, Math.max(col, 0));
};
this.textToScreenCoordinates = function(row, column) {
var canvasPos = this.scroller.getBoundingClientRect();
var pos = this.session.documentToScreenPosition(row, column);
var x = this.$padding + Math.round(pos.column * this.characterWidth);
var y = pos.row * this.lineHeight;
return {
pageX: canvasPos.left + x - this.scrollLeft,
pageY: canvasPos.top + y - this.scrollTop
};
};
this.visualizeFocus = function() {
dom.addCssClass(this.container, "ace_focus");
};
this.visualizeBlur = function() {
dom.removeCssClass(this.container, "ace_focus");
};
this.showComposition = function(position) {
if (!this.$composition)
this.$composition = {
keepTextAreaAtCursor: this.$keepTextAreaAtCursor,
cssText: this.textarea.style.cssText
};
this.$keepTextAreaAtCursor = true;
dom.addCssClass(this.textarea, "ace_composition");
this.textarea.style.cssText = "";
this.$moveTextAreaToCursor();
};
this.setCompositionText = function(text) {
this.$moveTextAreaToCursor();
};
this.hideComposition = function() {
if (!this.$composition)
return;
dom.removeCssClass(this.textarea, "ace_composition");
this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor;
this.textarea.style.cssText = this.$composition.cssText;
this.$composition = null;
};
this.setTheme = function(theme, cb) {
var _self = this;
this.$themeId = theme;
_self._dispatchEvent('themeChange',{theme:theme});
if (!theme || typeof theme == "string") {
var moduleName = theme || this.$options.theme.initialValue;
config.loadModule(["theme", moduleName], afterLoad);
} else {
afterLoad(theme);
}
function afterLoad(module) {
if (_self.$themeId != theme)
return cb && cb();
if (!module || !module.cssClass)
throw new Error("couldn't load module " + theme + " or it didn't call define");
dom.importCssString(
module.cssText,
module.cssClass,
_self.container.ownerDocument
);
if (_self.theme)
dom.removeCssClass(_self.container, _self.theme.cssClass);
var padding = "padding" in module ? module.padding
: "padding" in (_self.theme || {}) ? 4 : _self.$padding;
if (_self.$padding && padding != _self.$padding)
_self.setPadding(padding);
_self.$theme = module.cssClass;
_self.theme = module;
dom.addCssClass(_self.container, module.cssClass);
dom.setCssClass(_self.container, "ace_dark", module.isDark);
if (_self.$size) {
_self.$size.width = 0;
_self.$updateSizeAsync();
}
_self._dispatchEvent('themeLoaded', {theme:module});
cb && cb();
}
};
this.getTheme = function() {
return this.$themeId;
};
this.setStyle = function(style, include) {
dom.setCssClass(this.container, style, include !== false);
};
this.unsetStyle = function(style) {
dom.removeCssClass(this.container, style);
};
this.setCursorStyle = function(style) {
if (this.scroller.style.cursor != style)
this.scroller.style.cursor = style;
};
this.setMouseCursor = function(cursorStyle) {
this.scroller.style.cursor = cursorStyle;
};
this.destroy = function() {
this.$textLayer.destroy();
this.$cursorLayer.destroy();
};
}).call(VirtualRenderer.prototype);
config.defineOptions(VirtualRenderer.prototype, "renderer", {
animatedScroll: {initialValue: false},
showInvisibles: {
set: function(value) {
if (this.$textLayer.setShowInvisibles(value))
this.$loop.schedule(this.CHANGE_TEXT);
},
initialValue: false
},
showPrintMargin: {
set: function() { this.$updatePrintMargin(); },
initialValue: true
},
printMarginColumn: {
set: function() { this.$updatePrintMargin(); },
initialValue: 80
},
printMargin: {
set: function(val) {
if (typeof val == "number")
this.$printMarginColumn = val;
this.$showPrintMargin = !!val;
this.$updatePrintMargin();
},
get: function() {
return this.$showPrintMargin && this.$printMarginColumn;
}
},
showGutter: {
set: function(show){
this.$gutter.style.display = show ? "block" : "none";
this.$loop.schedule(this.CHANGE_FULL);
this.onGutterResize();
},
initialValue: true
},
fadeFoldWidgets: {
set: function(show) {
dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show);
},
initialValue: false
},
showFoldWidgets: {
set: function(show) {this.$gutterLayer.setShowFoldWidgets(show)},
initialValue: true
},
showLineNumbers: {
set: function(show) {
this.$gutterLayer.setShowLineNumbers(show);
this.$loop.schedule(this.CHANGE_GUTTER);
},
initialValue: true
},
displayIndentGuides: {
set: function(show) {
if (this.$textLayer.setDisplayIndentGuides(show))
this.$loop.schedule(this.CHANGE_TEXT);
},
initialValue: true
},
highlightGutterLine: {
set: function(shouldHighlight) {
if (!this.$gutterLineHighlight) {
this.$gutterLineHighlight = dom.createElement("div");
this.$gutterLineHighlight.className = "ace_gutter-active-line";
this.$gutter.appendChild(this.$gutterLineHighlight);
return;
}
this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none";
if (this.$cursorLayer.$pixelPos)
this.$updateGutterLineHighlight();
},
initialValue: false,
value: true
},
hScrollBarAlwaysVisible: {
set: function(val) {
if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: false
},
vScrollBarAlwaysVisible: {
set: function(val) {
if (!this.$vScrollBarAlwaysVisible || !this.$vScroll)
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: false
},
fontSize: {
set: function(size) {
if (typeof size == "number")
size = size + "px";
this.container.style.fontSize = size;
this.updateFontSize();
},
initialValue: 12
},
fontFamily: {
set: function(name) {
this.container.style.fontFamily = name;
this.updateFontSize();
}
},
maxLines: {
set: function(val) {
this.updateFull();
}
},
minLines: {
set: function(val) {
this.updateFull();
}
},
maxPixelHeight: {
set: function(val) {
this.updateFull();
},
initialValue: 0
},
scrollPastEnd: {
set: function(val) {
val = +val || 0;
if (this.$scrollPastEnd == val)
return;
this.$scrollPastEnd = val;
this.$loop.schedule(this.CHANGE_SCROLL);
},
initialValue: 0,
handlesSet: true
},
fixedWidthGutter: {
set: function(val) {
this.$gutterLayer.$fixedWidth = !!val;
this.$loop.schedule(this.CHANGE_GUTTER);
}
},
theme: {
set: function(val) { this.setTheme(val) },
get: function() { return this.$themeId || this.theme; },
initialValue: "./theme/textmate",
handlesSet: true
}
});
exports.VirtualRenderer = VirtualRenderer;
});
ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var net = acequire("../lib/net");
var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
var config = acequire("../config");
var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl) {
this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
this.changeListener = this.changeListener.bind(this);
this.onMessage = this.onMessage.bind(this);
if (acequire.nameToUrl && !acequire.toUrl)
acequire.toUrl = acequire.nameToUrl;
if (config.get("packaged") || !acequire.toUrl) {
workerUrl = workerUrl || config.moduleUrl(mod.id, "worker")
} else {
var normalizePath = this.$normalizePath;
workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_"));
var tlns = {};
topLevelNamespaces.forEach(function(ns) {
tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, ""));
});
}
try {
var workerSrc = mod.src;
var Blob = __webpack_require__(46);
var blob = new Blob([ workerSrc ], { type: 'application/javascript' });
var blobUrl = (window.URL || window.webkitURL).createObjectURL(blob);
this.$worker = new Worker(blobUrl);
} catch(e) {
if (e instanceof window.DOMException) {
var blob = this.$workerBlob(workerUrl);
var URL = window.URL || window.webkitURL;
var blobURL = URL.createObjectURL(blob);
this.$worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
} else {
throw e;
}
}
this.$worker.postMessage({
init : true,
tlns : tlns,
module : mod.id,
classname : classname
});
this.callbackId = 1;
this.callbacks = {};
this.$worker.onmessage = this.onMessage;
};
(function(){
oop.implement(this, EventEmitter);
this.onMessage = function(e) {
var msg = e.data;
switch(msg.type) {
case "event":
this._signal(msg.name, {data: msg.data});
break;
case "call":
var callback = this.callbacks[msg.id];
if (callback) {
callback(msg.data);
delete this.callbacks[msg.id];
}
break;
case "error":
this.reportError(msg.data);
break;
case "log":
window.console && console.log && console.log.apply(console, msg.data);
break;
}
};
this.reportError = function(err) {
window.console && console.error && console.error(err);
};
this.$normalizePath = function(path) {
return net.qualifyURL(path);
};
this.terminate = function() {
this._signal("terminate", {});
this.deltaQueue = null;
this.$worker.terminate();
this.$worker = null;
if (this.$doc)
this.$doc.off("change", this.changeListener);
this.$doc = null;
};
this.send = function(cmd, args) {
this.$worker.postMessage({command: cmd, args: args});
};
this.call = function(cmd, args, callback) {
if (callback) {
var id = this.callbackId++;
this.callbacks[id] = callback;
args.push(id);
}
this.send(cmd, args);
};
this.emit = function(event, data) {
try {
this.$worker.postMessage({event: event, data: {data: data.data}});
}
catch(ex) {
console.error(ex.stack);
}
};
this.attachToDocument = function(doc) {
if(this.$doc)
this.terminate();
this.$doc = doc;
this.call("setValue", [doc.getValue()]);
doc.on("change", this.changeListener);
};
this.changeListener = function(delta) {
if (!this.deltaQueue) {
this.deltaQueue = [];
setTimeout(this.$sendDeltaQueue, 0);
}
if (delta.action == "insert")
this.deltaQueue.push(delta.start, delta.lines);
else
this.deltaQueue.push(delta.start, delta.end);
};
this.$sendDeltaQueue = function() {
var q = this.deltaQueue;
if (!q) return;
this.deltaQueue = null;
if (q.length > 50 && q.length > this.$doc.getLength() >> 1) {
this.call("setValue", [this.$doc.getValue()]);
} else
this.emit("change", {data: q});
};
this.$workerBlob = function(workerUrl) {
var script = "importScripts('" + net.qualifyURL(workerUrl) + "');";
try {
return new Blob([script], {"type": "application/javascript"});
} catch (e) { // Backwards-compatibility
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
var blobBuilder = new BlobBuilder();
blobBuilder.append(script);
return blobBuilder.getBlob("application/javascript");
}
};
}).call(WorkerClient.prototype);
var UIWorkerClient = function(topLevelNamespaces, mod, classname) {
this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
this.changeListener = this.changeListener.bind(this);
this.callbackId = 1;
this.callbacks = {};
this.messageBuffer = [];
var main = null;
var emitSync = false;
var sender = Object.create(EventEmitter);
var _self = this;
this.$worker = {};
this.$worker.terminate = function() {};
this.$worker.postMessage = function(e) {
_self.messageBuffer.push(e);
if (main) {
if (emitSync)
setTimeout(processNext);
else
processNext();
}
};
this.setEmitSync = function(val) { emitSync = val };
var processNext = function() {
var msg = _self.messageBuffer.shift();
if (msg.command)
main[msg.command].apply(main, msg.args);
else if (msg.event)
sender._signal(msg.event, msg.data);
};
sender.postMessage = function(msg) {
_self.onMessage({data: msg});
};
sender.callback = function(data, callbackId) {
this.postMessage({type: "call", id: callbackId, data: data});
};
sender.emit = function(name, data) {
this.postMessage({type: "event", name: name, data: data});
};
config.loadModule(["worker", mod], function(Main) {
main = new Main[classname](sender);
while (_self.messageBuffer.length)
processNext();
});
};
UIWorkerClient.prototype = WorkerClient.prototype;
exports.UIWorkerClient = UIWorkerClient;
exports.WorkerClient = WorkerClient;
});
ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) {
"use strict";
var Range = acequire("./range").Range;
var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
var oop = acequire("./lib/oop");
var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) {
var _self = this;
this.length = length;
this.session = session;
this.doc = session.getDocument();
this.mainClass = mainClass;
this.othersClass = othersClass;
this.$onUpdate = this.onUpdate.bind(this);
this.doc.on("change", this.$onUpdate);
this.$others = others;
this.$onCursorChange = function() {
setTimeout(function() {
_self.onCursorChange();
});
};
this.$pos = pos;
var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1};
this.$undoStackDepth = undoStack.length;
this.setup();
session.selection.on("changeCursor", this.$onCursorChange);
};
(function() {
oop.implement(this, EventEmitter);
this.setup = function() {
var _self = this;
var doc = this.doc;
var session = this.session;
this.selectionBefore = session.selection.toJSON();
if (session.selection.inMultiSelectMode)
session.selection.toSingleRange();
this.pos = doc.createAnchor(this.$pos.row, this.$pos.column);
var pos = this.pos;
pos.$insertRight = true;
pos.detach();
pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false);
this.others = [];
this.$others.forEach(function(other) {
var anchor = doc.createAnchor(other.row, other.column);
anchor.$insertRight = true;
anchor.detach();
_self.others.push(anchor);
});
session.setUndoSelect(false);
};
this.showOtherMarkers = function() {
if (this.othersActive) return;
var session = this.session;
var _self = this;
this.othersActive = true;
this.others.forEach(function(anchor) {
anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false);
});
};
this.hideOtherMarkers = function() {
if (!this.othersActive) return;
this.othersActive = false;
for (var i = 0; i < this.others.length; i++) {
this.session.removeMarker(this.others[i].markerId);
}
};
this.onUpdate = function(delta) {
if (this.$updating)
return this.updateAnchors(delta);
var range = delta;
if (range.start.row !== range.end.row) return;
if (range.start.row !== this.pos.row) return;
this.$updating = true;
var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column;
var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1;
var distanceFromStart = range.start.column - this.pos.column;
this.updateAnchors(delta);
if (inMainRange)
this.length += lengthDiff;
if (inMainRange && !this.session.$fromUndo) {
if (delta.action === 'insert') {
for (var i = this.others.length - 1; i >= 0; i--) {
var otherPos = this.others[i];
var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
this.doc.insertMergedLines(newPos, delta.lines);
}
} else if (delta.action === 'remove') {
for (var i = this.others.length - 1; i >= 0; i--) {
var otherPos = this.others[i];
var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff));
}
}
}
this.$updating = false;
this.updateMarkers();
};
this.updateAnchors = function(delta) {
this.pos.onChange(delta);
for (var i = this.others.length; i--;)
this.others[i].onChange(delta);
this.updateMarkers();
};
this.updateMarkers = function() {
if (this.$updating)
return;
var _self = this;
var session = this.session;
var updateMarker = function(pos, className) {
session.removeMarker(pos.markerId);
pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false);
};
updateMarker(this.pos, this.mainClass);
for (var i = this.others.length; i--;)
updateMarker(this.others[i], this.othersClass);
};
this.onCursorChange = function(event) {
if (this.$updating || !this.session) return;
var pos = this.session.selection.getCursor();
if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) {
this.showOtherMarkers();
this._emit("cursorEnter", event);
} else {
this.hideOtherMarkers();
this._emit("cursorLeave", event);
}
};
this.detach = function() {
this.session.removeMarker(this.pos && this.pos.markerId);
this.hideOtherMarkers();
this.doc.removeEventListener("change", this.$onUpdate);
this.session.selection.removeEventListener("changeCursor", this.$onCursorChange);
this.session.setUndoSelect(true);
this.session = null;
};
this.cancel = function() {
if (this.$undoStackDepth === -1)
return;
var undoManager = this.session.getUndoManager();
var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth;
for (var i = 0; i < undosRequired; i++) {
undoManager.undo(true);
}
if (this.selectionBefore)
this.session.selection.fromJSON(this.selectionBefore);
};
}).call(PlaceHolder.prototype);
exports.PlaceHolder = PlaceHolder;
});
ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) {
var event = acequire("../lib/event");
var useragent = acequire("../lib/useragent");
function isSamePoint(p1, p2) {
return p1.row == p2.row && p1.column == p2.column;
}
function onMouseDown(e) {
var ev = e.domEvent;
var alt = ev.altKey;
var shift = ev.shiftKey;
var ctrl = ev.ctrlKey;
var accel = e.getAccelKey();
var button = e.getButton();
if (ctrl && useragent.isMac)
button = ev.button;
if (e.editor.inMultiSelectMode && button == 2) {
e.editor.textInput.onContextMenu(e.domEvent);
return;
}
if (!ctrl && !alt && !accel) {
if (button === 0 && e.editor.inMultiSelectMode)
e.editor.exitMultiSelectMode();
return;
}
if (button !== 0)
return;
var editor = e.editor;
var selection = editor.selection;
var isMultiSelect = editor.inMultiSelectMode;
var pos = e.getDocumentPosition();
var cursor = selection.getCursor();
var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor));
var mouseX = e.x, mouseY = e.y;
var onMouseSelection = function(e) {
mouseX = e.clientX;
mouseY = e.clientY;
};
var session = editor.session;
var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
var screenCursor = screenAnchor;
var selectionMode;
if (editor.$mouseHandler.$enableJumpToDef) {
if (ctrl && alt || accel && alt)
selectionMode = shift ? "block" : "add";
else if (alt && editor.$blockSelectEnabled)
selectionMode = "block";
} else {
if (accel && !alt) {
selectionMode = "add";
if (!isMultiSelect && shift)
return;
} else if (alt && editor.$blockSelectEnabled) {
selectionMode = "block";
}
}
if (selectionMode && useragent.isMac && ev.ctrlKey) {
editor.$mouseHandler.cancelContextMenu();
}
if (selectionMode == "add") {
if (!isMultiSelect && inSelection)
return; // dragging
if (!isMultiSelect) {
var range = selection.toOrientedRange();
editor.addSelectionMarker(range);
}
var oldRange = selection.rangeList.rangeAtPoint(pos);
editor.$blockScrolling++;
editor.inVirtualSelectionMode = true;
if (shift) {
oldRange = null;
range = selection.ranges[0] || range;
editor.removeSelectionMarker(range);
}
editor.once("mouseup", function() {
var tmpSel = selection.toOrientedRange();
if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor))
selection.substractPoint(tmpSel.cursor);
else {
if (shift) {
selection.substractPoint(range.cursor);
} else if (range) {
editor.removeSelectionMarker(range);
selection.addRange(range);
}
selection.addRange(tmpSel);
}
editor.$blockScrolling--;
editor.inVirtualSelectionMode = false;
});
} else if (selectionMode == "block") {
e.stop();
editor.inVirtualSelectionMode = true;
var initialRange;
var rectSel = [];
var blockSelect = function() {
var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column);
if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead))
return;
screenCursor = newCursor;
editor.$blockScrolling++;
editor.selection.moveToPosition(cursor);
editor.renderer.scrollCursorIntoView();
editor.removeSelectionMarkers(rectSel);
rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor);
if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty())
rectSel[0] = editor.$mouseHandler.$clickSelection.clone();
rectSel.forEach(editor.addSelectionMarker, editor);
editor.updateSelectionMarkers();
editor.$blockScrolling--;
};
editor.$blockScrolling++;
if (isMultiSelect && !accel) {
selection.toSingleRange();
} else if (!isMultiSelect && accel) {
initialRange = selection.toOrientedRange();
editor.addSelectionMarker(initialRange);
}
if (shift)
screenAnchor = session.documentToScreenPosition(selection.lead);
else
selection.moveToPosition(pos);
editor.$blockScrolling--;
screenCursor = {row: -1, column: -1};
var onMouseSelectionEnd = function(e) {
clearInterval(timerId);
editor.removeSelectionMarkers(rectSel);
if (!rectSel.length)
rectSel = [selection.toOrientedRange()];
editor.$blockScrolling++;
if (initialRange) {
editor.removeSelectionMarker(initialRange);
selection.toSingleRange(initialRange);
}
for (var i = 0; i < rectSel.length; i++)
selection.addRange(rectSel[i]);
editor.inVirtualSelectionMode = false;
editor.$mouseHandler.$clickSelection = null;
editor.$blockScrolling--;
};
var onSelectionInterval = blockSelect;
event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
var timerId = setInterval(function() {onSelectionInterval();}, 20);
return e.preventDefault();
}
}
exports.onMouseDown = onMouseDown;
});
ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) {
exports.defaultCommands = [{
name: "addCursorAbove",
exec: function(editor) { editor.selectMoreLines(-1); },
bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorBelow",
exec: function(editor) { editor.selectMoreLines(1); },
bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorAboveSkipCurrent",
exec: function(editor) { editor.selectMoreLines(-1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "addCursorBelowSkipCurrent",
exec: function(editor) { editor.selectMoreLines(1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectMoreBefore",
exec: function(editor) { editor.selectMore(-1); },
bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectMoreAfter",
exec: function(editor) { editor.selectMore(1); },
bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectNextBefore",
exec: function(editor) { editor.selectMore(-1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "selectNextAfter",
exec: function(editor) { editor.selectMore(1, true); },
bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"},
scrollIntoView: "cursor",
readOnly: true
}, {
name: "splitIntoLines",
exec: function(editor) { editor.multiSelect.splitIntoLines(); },
bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"},
readOnly: true
}, {
name: "alignCursors",
exec: function(editor) { editor.alignCursors(); },
bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"},
scrollIntoView: "cursor"
}, {
name: "findAll",
exec: function(editor) { editor.findAll(); },
bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"},
scrollIntoView: "cursor",
readOnly: true
}];
exports.multiSelectCommands = [{
name: "singleSelection",
bindKey: "esc",
exec: function(editor) { editor.exitMultiSelectMode(); },
scrollIntoView: "cursor",
readOnly: true,
isAvailable: function(editor) {return editor && editor.inMultiSelectMode}
}];
var HashHandler = acequire("../keyboard/hash_handler").HashHandler;
exports.keyboardHandler = new HashHandler(exports.multiSelectCommands);
});
ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) {
var RangeList = acequire("./range_list").RangeList;
var Range = acequire("./range").Range;
var Selection = acequire("./selection").Selection;
var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown;
var event = acequire("./lib/event");
var lang = acequire("./lib/lang");
var commands = acequire("./commands/multi_select_commands");
exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands);
var Search = acequire("./search").Search;
var search = new Search();
function find(session, needle, dir) {
search.$options.wrap = true;
search.$options.needle = needle;
search.$options.backwards = dir == -1;
return search.find(session);
}
var EditSession = acequire("./edit_session").EditSession;
(function() {
this.getSelectionMarkers = function() {
return this.$selectionMarkers;
};
}).call(EditSession.prototype);
(function() {
this.ranges = null;
this.rangeList = null;
this.addRange = function(range, $blockChangeEvents) {
if (!range)
return;
if (!this.inMultiSelectMode && this.rangeCount === 0) {
var oldRange = this.toOrientedRange();
this.rangeList.add(oldRange);
this.rangeList.add(range);
if (this.rangeList.ranges.length != 2) {
this.rangeList.removeAll();
return $blockChangeEvents || this.fromOrientedRange(range);
}
this.rangeList.removeAll();
this.rangeList.add(oldRange);
this.$onAddRange(oldRange);
}
if (!range.cursor)
range.cursor = range.end;
var removed = this.rangeList.add(range);
this.$onAddRange(range);
if (removed.length)
this.$onRemoveRange(removed);
if (this.rangeCount > 1 && !this.inMultiSelectMode) {
this._signal("multiSelect");
this.inMultiSelectMode = true;
this.session.$undoSelect = false;
this.rangeList.attach(this.session);
}
return $blockChangeEvents || this.fromOrientedRange(range);
};
this.toSingleRange = function(range) {
range = range || this.ranges[0];
var removed = this.rangeList.removeAll();
if (removed.length)
this.$onRemoveRange(removed);
range && this.fromOrientedRange(range);
};
this.substractPoint = function(pos) {
var removed = this.rangeList.substractPoint(pos);
if (removed) {
this.$onRemoveRange(removed);
return removed[0];
}
};
this.mergeOverlappingRanges = function() {
var removed = this.rangeList.merge();
if (removed.length)
this.$onRemoveRange(removed);
else if(this.ranges[0])
this.fromOrientedRange(this.ranges[0]);
};
this.$onAddRange = function(range) {
this.rangeCount = this.rangeList.ranges.length;
this.ranges.unshift(range);
this._signal("addRange", {range: range});
};
this.$onRemoveRange = function(removed) {
this.rangeCount = this.rangeList.ranges.length;
if (this.rangeCount == 1 && this.inMultiSelectMode) {
var lastRange = this.rangeList.ranges.pop();
removed.push(lastRange);
this.rangeCount = 0;
}
for (var i = removed.length; i--; ) {
var index = this.ranges.indexOf(removed[i]);
this.ranges.splice(index, 1);
}
this._signal("removeRange", {ranges: removed});
if (this.rangeCount === 0 && this.inMultiSelectMode) {
this.inMultiSelectMode = false;
this._signal("singleSelect");
this.session.$undoSelect = true;
this.rangeList.detach(this.session);
}
lastRange = lastRange || this.ranges[0];
if (lastRange && !lastRange.isEqual(this.getRange()))
this.fromOrientedRange(lastRange);
};
this.$initRangeList = function() {
if (this.rangeList)
return;
this.rangeList = new RangeList();
this.ranges = [];
this.rangeCount = 0;
};
this.getAllRanges = function() {
return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()];
};
this.splitIntoLines = function () {
if (this.rangeCount > 1) {
var ranges = this.rangeList.ranges;
var lastRange = ranges[ranges.length - 1];
var range = Range.fromPoints(ranges[0].start, lastRange.end);
this.toSingleRange();
this.setSelectionRange(range, lastRange.cursor == lastRange.start);
} else {
var range = this.getRange();
var isBackwards = this.isBackwards();
var startRow = range.start.row;
var endRow = range.end.row;
if (startRow == endRow) {
if (isBackwards)
var start = range.end, end = range.start;
else
var start = range.start, end = range.end;
this.addRange(Range.fromPoints(end, end));
this.addRange(Range.fromPoints(start, start));
return;
}
var rectSel = [];
var r = this.getLineRange(startRow, true);
r.start.column = range.start.column;
rectSel.push(r);
for (var i = startRow + 1; i < endRow; i++)
rectSel.push(this.getLineRange(i, true));
r = this.getLineRange(endRow, true);
r.end.column = range.end.column;
rectSel.push(r);
rectSel.forEach(this.addRange, this);
}
};
this.toggleBlockSelection = function () {
if (this.rangeCount > 1) {
var ranges = this.rangeList.ranges;
var lastRange = ranges[ranges.length - 1];
var range = Range.fromPoints(ranges[0].start, lastRange.end);
this.toSingleRange();
this.setSelectionRange(range, lastRange.cursor == lastRange.start);
} else {
var cursor = this.session.documentToScreenPosition(this.selectionLead);
var anchor = this.session.documentToScreenPosition(this.selectionAnchor);
var rectSel = this.rectangularRangeBlock(cursor, anchor);
rectSel.forEach(this.addRange, this);
}
};
this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) {
var rectSel = [];
var xBackwards = screenCursor.column < screenAnchor.column;
if (xBackwards) {
var startColumn = screenCursor.column;
var endColumn = screenAnchor.column;
} else {
var startColumn = screenAnchor.column;
var endColumn = screenCursor.column;
}
var yBackwards = screenCursor.row < screenAnchor.row;
if (yBackwards) {
var startRow = screenCursor.row;
var endRow = screenAnchor.row;
} else {
var startRow = screenAnchor.row;
var endRow = screenCursor.row;
}
if (startColumn < 0)
startColumn = 0;
if (startRow < 0)
startRow = 0;
if (startRow == endRow)
includeEmptyLines = true;
for (var row = startRow; row <= endRow; row++) {
var range = Range.fromPoints(
this.session.screenToDocumentPosition(row, startColumn),
this.session.screenToDocumentPosition(row, endColumn)
);
if (range.isEmpty()) {
if (docEnd && isSamePoint(range.end, docEnd))
break;
var docEnd = range.end;
}
range.cursor = xBackwards ? range.start : range.end;
rectSel.push(range);
}
if (yBackwards)
rectSel.reverse();
if (!includeEmptyLines) {
var end = rectSel.length - 1;
while (rectSel[end].isEmpty() && end > 0)
end--;
if (end > 0) {
var start = 0;
while (rectSel[start].isEmpty())
start++;
}
for (var i = end; i >= start; i--) {
if (rectSel[i].isEmpty())
rectSel.splice(i, 1);
}
}
return rectSel;
};
}).call(Selection.prototype);
var Editor = acequire("./editor").Editor;
(function() {
this.updateSelectionMarkers = function() {
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.addSelectionMarker = function(orientedRange) {
if (!orientedRange.cursor)
orientedRange.cursor = orientedRange.end;
var style = this.getSelectionStyle();
orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style);
this.session.$selectionMarkers.push(orientedRange);
this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
return orientedRange;
};
this.removeSelectionMarker = function(range) {
if (!range.marker)
return;
this.session.removeMarker(range.marker);
var index = this.session.$selectionMarkers.indexOf(range);
if (index != -1)
this.session.$selectionMarkers.splice(index, 1);
this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
};
this.removeSelectionMarkers = function(ranges) {
var markerList = this.session.$selectionMarkers;
for (var i = ranges.length; i--; ) {
var range = ranges[i];
if (!range.marker)
continue;
this.session.removeMarker(range.marker);
var index = markerList.indexOf(range);
if (index != -1)
markerList.splice(index, 1);
}
this.session.selectionMarkerCount = markerList.length;
};
this.$onAddRange = function(e) {
this.addSelectionMarker(e.range);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onRemoveRange = function(e) {
this.removeSelectionMarkers(e.ranges);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onMultiSelect = function(e) {
if (this.inMultiSelectMode)
return;
this.inMultiSelectMode = true;
this.setStyle("ace_multiselect");
this.keyBinding.addKeyboardHandler(commands.keyboardHandler);
this.commands.setDefaultHandler("exec", this.$onMultiSelectExec);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
};
this.$onSingleSelect = function(e) {
if (this.session.multiSelect.inVirtualMode)
return;
this.inMultiSelectMode = false;
this.unsetStyle("ace_multiselect");
this.keyBinding.removeKeyboardHandler(commands.keyboardHandler);
this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
this._emit("changeSelection");
};
this.$onMultiSelectExec = function(e) {
var command = e.command;
var editor = e.editor;
if (!editor.multiSelect)
return;
if (!command.multiSelectAction) {
var result = command.exec(editor, e.args || {});
editor.multiSelect.addRange(editor.multiSelect.toOrientedRange());
editor.multiSelect.mergeOverlappingRanges();
} else if (command.multiSelectAction == "forEach") {
result = editor.forEachSelection(command, e.args);
} else if (command.multiSelectAction == "forEachLine") {
result = editor.forEachSelection(command, e.args, true);
} else if (command.multiSelectAction == "single") {
editor.exitMultiSelectMode();
result = command.exec(editor, e.args || {});
} else {
result = command.multiSelectAction(editor, e.args || {});
}
return result;
};
this.forEachSelection = function(cmd, args, options) {
if (this.inVirtualSelectionMode)
return;
var keepOrder = options && options.keepOrder;
var $byLines = options == true || options && options.$byLines
var session = this.session;
var selection = this.selection;
var rangeList = selection.rangeList;
var ranges = (keepOrder ? selection : rangeList).ranges;
var result;
if (!ranges.length)
return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
var reg = selection._eventRegistry;
selection._eventRegistry = {};
var tmpSel = new Selection(session);
this.inVirtualSelectionMode = true;
for (var i = ranges.length; i--;) {
if ($byLines) {
while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row)
i--;
}
tmpSel.fromOrientedRange(ranges[i]);
tmpSel.index = i;
this.selection = session.selection = tmpSel;
var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
if (!result && cmdResult !== undefined)
result = cmdResult;
tmpSel.toOrientedRange(ranges[i]);
}
tmpSel.detach();
this.selection = session.selection = selection;
this.inVirtualSelectionMode = false;
selection._eventRegistry = reg;
selection.mergeOverlappingRanges();
var anim = this.renderer.$scrollAnimation;
this.onCursorChange();
this.onSelectionChange();
if (anim && anim.from == anim.to)
this.renderer.animateScrolling(anim.from);
return result;
};
this.exitMultiSelectMode = function() {
if (!this.inMultiSelectMode || this.inVirtualSelectionMode)
return;
this.multiSelect.toSingleRange();
};
this.getSelectedText = function() {
var text = "";
if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
var ranges = this.multiSelect.rangeList.ranges;
var buf = [];
for (var i = 0; i < ranges.length; i++) {
buf.push(this.session.getTextRange(ranges[i]));
}
var nl = this.session.getDocument().getNewLineCharacter();
text = buf.join(nl);
if (text.length == (buf.length - 1) * nl.length)
text = "";
} else if (!this.selection.isEmpty()) {
text = this.session.getTextRange(this.getSelectionRange());
}
return text;
};
this.$checkMultiselectChange = function(e, anchor) {
if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
var range = this.multiSelect.ranges[0];
if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor)
return;
var pos = anchor == this.multiSelect.anchor
? range.cursor == range.start ? range.end : range.start
: range.cursor;
if (pos.row != anchor.row
|| this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column)
this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange());
}
};
this.findAll = function(needle, options, additive) {
options = options || {};
options.needle = needle || options.needle;
if (options.needle == undefined) {
var range = this.selection.isEmpty()
? this.selection.getWordRange()
: this.selection.getRange();
options.needle = this.session.getTextRange(range);
}
this.$search.set(options);
var ranges = this.$search.findAll(this.session);
if (!ranges.length)
return 0;
this.$blockScrolling += 1;
var selection = this.multiSelect;
if (!additive)
selection.toSingleRange(ranges[0]);
for (var i = ranges.length; i--; )
selection.addRange(ranges[i], true);
if (range && selection.rangeList.rangeAtPoint(range.start))
selection.addRange(range, true);
this.$blockScrolling -= 1;
return ranges.length;
};
this.selectMoreLines = function(dir, skip) {
var range = this.selection.toOrientedRange();
var isBackwards = range.cursor == range.end;
var screenLead = this.session.documentToScreenPosition(range.cursor);
if (this.selection.$desiredColumn)
screenLead.column = this.selection.$desiredColumn;
var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column);
if (!range.isEmpty()) {
var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start);
var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column);
} else {
var anchor = lead;
}
if (isBackwards) {
var newRange = Range.fromPoints(lead, anchor);
newRange.cursor = newRange.start;
} else {
var newRange = Range.fromPoints(anchor, lead);
newRange.cursor = newRange.end;
}
newRange.desiredColumn = screenLead.column;
if (!this.selection.inMultiSelectMode) {
this.selection.addRange(range);
} else {
if (skip)
var toRemove = range.cursor;
}
this.selection.addRange(newRange);
if (toRemove)
this.selection.substractPoint(toRemove);
};
this.transposeSelections = function(dir) {
var session = this.session;
var sel = session.multiSelect;
var all = sel.ranges;
for (var i = all.length; i--; ) {
var range = all[i];
if (range.isEmpty()) {
var tmp = session.getWordRange(range.start.row, range.start.column);
range.start.row = tmp.start.row;
range.start.column = tmp.start.column;
range.end.row = tmp.end.row;
range.end.column = tmp.end.column;
}
}
sel.mergeOverlappingRanges();
var words = [];
for (var i = all.length; i--; ) {
var range = all[i];
words.unshift(session.getTextRange(range));
}
if (dir < 0)
words.unshift(words.pop());
else
words.push(words.shift());
for (var i = all.length; i--; ) {
var range = all[i];
var tmp = range.clone();
session.replace(range, words[i]);
range.start.row = tmp.start.row;
range.start.column = tmp.start.column;
}
};
this.selectMore = function(dir, skip, stopAtFirst) {
var session = this.session;
var sel = session.multiSelect;
var range = sel.toOrientedRange();
if (range.isEmpty()) {
range = session.getWordRange(range.start.row, range.start.column);
range.cursor = dir == -1 ? range.start : range.end;
this.multiSelect.addRange(range);
if (stopAtFirst)
return;
}
var needle = session.getTextRange(range);
var newRange = find(session, needle, dir);
if (newRange) {
newRange.cursor = dir == -1 ? newRange.start : newRange.end;
this.$blockScrolling += 1;
this.session.unfold(newRange);
this.multiSelect.addRange(newRange);
this.$blockScrolling -= 1;
this.renderer.scrollCursorIntoView(null, 0.5);
}
if (skip)
this.multiSelect.substractPoint(range.cursor);
};
this.alignCursors = function() {
var session = this.session;
var sel = session.multiSelect;
var ranges = sel.ranges;
var row = -1;
var sameRowRanges = ranges.filter(function(r) {
if (r.cursor.row == row)
return true;
row = r.cursor.row;
});
if (!ranges.length || sameRowRanges.length == ranges.length - 1) {
var range = this.selection.getRange();
var fr = range.start.row, lr = range.end.row;
var guessRange = fr == lr;
if (guessRange) {
var max = this.session.getLength();
var line;
do {
line = this.session.getLine(lr);
} while (/[=:]/.test(line) && ++lr < max);
do {
line = this.session.getLine(fr);
} while (/[=:]/.test(line) && --fr > 0);
if (fr < 0) fr = 0;
if (lr >= max) lr = max - 1;
}
var lines = this.session.removeFullLines(fr, lr);
lines = this.$reAlignText(lines, guessRange);
this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n");
if (!guessRange) {
range.start.column = 0;
range.end.column = lines[lines.length - 1].length;
}
this.selection.setRange(range);
} else {
sameRowRanges.forEach(function(r) {
sel.substractPoint(r.cursor);
});
var maxCol = 0;
var minSpace = Infinity;
var spaceOffsets = ranges.map(function(r) {
var p = r.cursor;
var line = session.getLine(p.row);
var spaceOffset = line.substr(p.column).search(/\S/g);
if (spaceOffset == -1)
spaceOffset = 0;
if (p.column > maxCol)
maxCol = p.column;
if (spaceOffset < minSpace)
minSpace = spaceOffset;
return spaceOffset;
});
ranges.forEach(function(r, i) {
var p = r.cursor;
var l = maxCol - p.column;
var d = spaceOffsets[i] - minSpace;
if (l > d)
session.insert(p, lang.stringRepeat(" ", l - d));
else
session.remove(new Range(p.row, p.column, p.row, p.column - l + d));
r.start.column = r.end.column = maxCol;
r.start.row = r.end.row = p.row;
r.cursor = r.end;
});
sel.fromOrientedRange(ranges[0]);
this.renderer.updateCursor();
this.renderer.updateBackMarkers();
}
};
this.$reAlignText = function(lines, forceLeft) {
var isLeftAligned = true, isRightAligned = true;
var startW, textW, endW;
return lines.map(function(line) {
var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/);
if (!m)
return [line];
if (startW == null) {
startW = m[1].length;
textW = m[2].length;
endW = m[3].length;
return m;
}
if (startW + textW + endW != m[1].length + m[2].length + m[3].length)
isRightAligned = false;
if (startW != m[1].length)
isLeftAligned = false;
if (startW > m[1].length)
startW = m[1].length;
if (textW < m[2].length)
textW = m[2].length;
if (endW > m[3].length)
endW = m[3].length;
return m;
}).map(forceLeft ? alignLeft :
isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign);
function spaces(n) {
return lang.stringRepeat(" ", n);
}
function alignLeft(m) {
return !m[2] ? m[0] : spaces(startW) + m[2]
+ spaces(textW - m[2].length + endW)
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
function alignRight(m) {
return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2]
+ spaces(endW, " ")
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
function unAlign(m) {
return !m[2] ? m[0] : spaces(startW) + m[2]
+ spaces(endW)
+ m[4].replace(/^([=:])\s+/, "$1 ");
}
};
}).call(Editor.prototype);
function isSamePoint(p1, p2) {
return p1.row == p2.row && p1.column == p2.column;
}
exports.onSessionChange = function(e) {
var session = e.session;
if (session && !session.multiSelect) {
session.$selectionMarkers = [];
session.selection.$initRangeList();
session.multiSelect = session.selection;
}
this.multiSelect = session && session.multiSelect;
var oldSession = e.oldSession;
if (oldSession) {
oldSession.multiSelect.off("addRange", this.$onAddRange);
oldSession.multiSelect.off("removeRange", this.$onRemoveRange);
oldSession.multiSelect.off("multiSelect", this.$onMultiSelect);
oldSession.multiSelect.off("singleSelect", this.$onSingleSelect);
oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange);
oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange);
}
if (session) {
session.multiSelect.on("addRange", this.$onAddRange);
session.multiSelect.on("removeRange", this.$onRemoveRange);
session.multiSelect.on("multiSelect", this.$onMultiSelect);
session.multiSelect.on("singleSelect", this.$onSingleSelect);
session.multiSelect.lead.on("change", this.$checkMultiselectChange);
session.multiSelect.anchor.on("change", this.$checkMultiselectChange);
}
if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) {
if (session.selection.inMultiSelectMode)
this.$onMultiSelect();
else
this.$onSingleSelect();
}
};
function MultiSelect(editor) {
if (editor.$multiselectOnSessionChange)
return;
editor.$onAddRange = editor.$onAddRange.bind(editor);
editor.$onRemoveRange = editor.$onRemoveRange.bind(editor);
editor.$onMultiSelect = editor.$onMultiSelect.bind(editor);
editor.$onSingleSelect = editor.$onSingleSelect.bind(editor);
editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor);
editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor);
editor.$multiselectOnSessionChange(editor);
editor.on("changeSession", editor.$multiselectOnSessionChange);
editor.on("mousedown", onMouseDown);
editor.commands.addCommands(commands.defaultCommands);
addAltCursorListeners(editor);
}
function addAltCursorListeners(editor){
var el = editor.textInput.getElement();
var altCursor = false;
event.addListener(el, "keydown", function(e) {
var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey);
if (editor.$blockSelectEnabled && altDown) {
if (!altCursor) {
editor.renderer.setMouseCursor("crosshair");
altCursor = true;
}
} else if (altCursor) {
reset();
}
});
event.addListener(el, "keyup", reset);
event.addListener(el, "blur", reset);
function reset(e) {
if (altCursor) {
editor.renderer.setMouseCursor("");
altCursor = false;
}
}
}
exports.MultiSelect = MultiSelect;
acequire("./config").defineOptions(Editor.prototype, "editor", {
enableMultiselect: {
set: function(val) {
MultiSelect(this);
if (val) {
this.on("changeSession", this.$multiselectOnSessionChange);
this.on("mousedown", onMouseDown);
} else {
this.off("changeSession", this.$multiselectOnSessionChange);
this.off("mousedown", onMouseDown);
}
},
value: true
},
enableBlockSelect: {
set: function(val) {
this.$blockSelectEnabled = val;
},
value: true
}
});
});
ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1)
return;
var startColumn = column || line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
var level = session.getLine(row).search(re);
if (level == -1)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = session.getFoldWidget(end.row);
if (fw == "start" && end.row > start.row) {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
this.closingBracketBlock = function(session, bracket, row, column, typeRe) {
var end = {row: row, column: column};
var start = session.$findOpeningBracket(bracket, end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
"use strict";
exports.isDark = false;
exports.cssClass = "ace-tm";
exports.cssText = ".ace-tm .ace_gutter {\
background: #f0f0f0;\
color: #333;\
}\
.ace-tm .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-tm .ace_fold {\
background-color: #6B72E6;\
}\
.ace-tm {\
background-color: #FFFFFF;\
color: black;\
}\
.ace-tm .ace_cursor {\
color: black;\
}\
.ace-tm .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-tm .ace_storage,\
.ace-tm .ace_keyword {\
color: blue;\
}\
.ace-tm .ace_constant {\
color: rgb(197, 6, 11);\
}\
.ace-tm .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-tm .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-tm .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_invalid {\
background-color: rgba(255, 0, 0, 0.1);\
color: red;\
}\
.ace-tm .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-tm .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_support.ace_type,\
.ace-tm .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
.ace-tm .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-tm .ace_string {\
color: rgb(3, 106, 7);\
}\
.ace-tm .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-tm .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-tm .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-tm .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-tm .ace_variable {\
color: rgb(49, 132, 149);\
}\
.ace-tm .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-tm .ace_entity.ace_name.ace_function {\
color: #0000A2;\
}\
.ace-tm .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-tm .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-tm .ace_meta.ace_tag {\
color:rgb(0, 22, 142);\
}\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-tm.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px white;\
}\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-tm .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-tm .ace_gutter-active-line {\
background-color : #dcdcdc;\
}\
.ace-tm .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-tm .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}\
";
var dom = acequire("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) {
"use strict";
var oop = acequire("./lib/oop");
var dom = acequire("./lib/dom");
var Range = acequire("./range").Range;
function LineWidgets(session) {
this.session = session;
this.session.widgetManager = this;
this.session.getRowLength = this.getRowLength;
this.session.$getWidgetScreenLength = this.$getWidgetScreenLength;
this.updateOnChange = this.updateOnChange.bind(this);
this.renderWidgets = this.renderWidgets.bind(this);
this.measureWidgets = this.measureWidgets.bind(this);
this.session._changedWidgets = [];
this.$onChangeEditor = this.$onChangeEditor.bind(this);
this.session.on("change", this.updateOnChange);
this.session.on("changeFold", this.updateOnFold);
this.session.on("changeEditor", this.$onChangeEditor);
}
(function() {
this.getRowLength = function(row) {
var h;
if (this.lineWidgets)
h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
else
h = 0;
if (!this.$useWrapMode || !this.$wrapData[row]) {
return 1 + h;
} else {
return this.$wrapData[row].length + 1 + h;
}
};
this.$getWidgetScreenLength = function() {
var screenRows = 0;
this.lineWidgets.forEach(function(w){
if (w && w.rowCount && !w.hidden)
screenRows += w.rowCount;
});
return screenRows;
};
this.$onChangeEditor = function(e) {
this.attach(e.editor);
};
this.attach = function(editor) {
if (editor && editor.widgetManager && editor.widgetManager != this)
editor.widgetManager.detach();
if (this.editor == editor)
return;
this.detach();
this.editor = editor;
if (editor) {
editor.widgetManager = this;
editor.renderer.on("beforeRender", this.measureWidgets);
editor.renderer.on("afterRender", this.renderWidgets);
}
};
this.detach = function(e) {
var editor = this.editor;
if (!editor)
return;
this.editor = null;
editor.widgetManager = null;
editor.renderer.off("beforeRender", this.measureWidgets);
editor.renderer.off("afterRender", this.renderWidgets);
var lineWidgets = this.session.lineWidgets;
lineWidgets && lineWidgets.forEach(function(w) {
if (w && w.el && w.el.parentNode) {
w._inDocument = false;
w.el.parentNode.removeChild(w.el);
}
});
};
this.updateOnFold = function(e, session) {
var lineWidgets = session.lineWidgets;
if (!lineWidgets || !e.action)
return;
var fold = e.data;
var start = fold.start.row;
var end = fold.end.row;
var hide = e.action == "add";
for (var i = start + 1; i < end; i++) {
if (lineWidgets[i])
lineWidgets[i].hidden = hide;
}
if (lineWidgets[end]) {
if (hide) {
if (!lineWidgets[start])
lineWidgets[start] = lineWidgets[end];
else
lineWidgets[end].hidden = hide;
} else {
if (lineWidgets[start] == lineWidgets[end])
lineWidgets[start] = undefined;
lineWidgets[end].hidden = hide;
}
}
};
this.updateOnChange = function(delta) {
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets) return;
var startRow = delta.start.row;
var len = delta.end.row - startRow;
if (len === 0) {
} else if (delta.action == 'remove') {
var removed = lineWidgets.splice(startRow + 1, len);
removed.forEach(function(w) {
w && this.removeLineWidget(w);
}, this);
this.$updateRows();
} else {
var args = new Array(len);
args.unshift(startRow, 0);
lineWidgets.splice.apply(lineWidgets, args);
this.$updateRows();
}
};
this.$updateRows = function() {
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets) return;
var noWidgets = true;
lineWidgets.forEach(function(w, i) {
if (w) {
noWidgets = false;
w.row = i;
while (w.$oldWidget) {
w.$oldWidget.row = i;
w = w.$oldWidget;
}
}
});
if (noWidgets)
this.session.lineWidgets = null;
};
this.addLineWidget = function(w) {
if (!this.session.lineWidgets)
this.session.lineWidgets = new Array(this.session.getLength());
var old = this.session.lineWidgets[w.row];
if (old) {
w.$oldWidget = old;
if (old.el && old.el.parentNode) {
old.el.parentNode.removeChild(old.el);
old._inDocument = false;
}
}
this.session.lineWidgets[w.row] = w;
w.session = this.session;
var renderer = this.editor.renderer;
if (w.html && !w.el) {
w.el = dom.createElement("div");
w.el.innerHTML = w.html;
}
if (w.el) {
dom.addCssClass(w.el, "ace_lineWidgetContainer");
w.el.style.position = "absolute";
w.el.style.zIndex = 5;
renderer.container.appendChild(w.el);
w._inDocument = true;
}
if (!w.coverGutter) {
w.el.style.zIndex = 3;
}
if (w.pixelHeight == null) {
w.pixelHeight = w.el.offsetHeight;
}
if (w.rowCount == null) {
w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight;
}
var fold = this.session.getFoldAt(w.row, 0);
w.$fold = fold;
if (fold) {
var lineWidgets = this.session.lineWidgets;
if (w.row == fold.end.row && !lineWidgets[fold.start.row])
lineWidgets[fold.start.row] = w;
else
w.hidden = true;
}
this.session._emit("changeFold", {data:{start:{row: w.row}}});
this.$updateRows();
this.renderWidgets(null, renderer);
this.onWidgetChanged(w);
return w;
};
this.removeLineWidget = function(w) {
w._inDocument = false;
w.session = null;
if (w.el && w.el.parentNode)
w.el.parentNode.removeChild(w.el);
if (w.editor && w.editor.destroy) try {
w.editor.destroy();
} catch(e){}
if (this.session.lineWidgets) {
var w1 = this.session.lineWidgets[w.row]
if (w1 == w) {
this.session.lineWidgets[w.row] = w.$oldWidget;
if (w.$oldWidget)
this.onWidgetChanged(w.$oldWidget);
} else {
while (w1) {
if (w1.$oldWidget == w) {
w1.$oldWidget = w.$oldWidget;
break;
}
w1 = w1.$oldWidget;
}
}
}
this.session._emit("changeFold", {data:{start:{row: w.row}}});
this.$updateRows();
};
this.getWidgetsAtRow = function(row) {
var lineWidgets = this.session.lineWidgets;
var w = lineWidgets && lineWidgets[row];
var list = [];
while (w) {
list.push(w);
w = w.$oldWidget;
}
return list;
};
this.onWidgetChanged = function(w) {
this.session._changedWidgets.push(w);
this.editor && this.editor.renderer.updateFull();
};
this.measureWidgets = function(e, renderer) {
var changedWidgets = this.session._changedWidgets;
var config = renderer.layerConfig;
if (!changedWidgets || !changedWidgets.length) return;
var min = Infinity;
for (var i = 0; i < changedWidgets.length; i++) {
var w = changedWidgets[i];
if (!w || !w.el) continue;
if (w.session != this.session) continue;
if (!w._inDocument) {
if (this.session.lineWidgets[w.row] != w)
continue;
w._inDocument = true;
renderer.container.appendChild(w.el);
}
w.h = w.el.offsetHeight;
if (!w.fixedWidth) {
w.w = w.el.offsetWidth;
w.screenWidth = Math.ceil(w.w / config.characterWidth);
}
var rowCount = w.h / config.lineHeight;
if (w.coverLine) {
rowCount -= this.session.getRowLineCount(w.row);
if (rowCount < 0)
rowCount = 0;
}
if (w.rowCount != rowCount) {
w.rowCount = rowCount;
if (w.row < min)
min = w.row;
}
}
if (min != Infinity) {
this.session._emit("changeFold", {data:{start:{row: min}}});
this.session.lineWidgetWidth = null;
}
this.session._changedWidgets = [];
};
this.renderWidgets = function(e, renderer) {
var config = renderer.layerConfig;
var lineWidgets = this.session.lineWidgets;
if (!lineWidgets)
return;
var first = Math.min(this.firstRow, config.firstRow);
var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length);
while (first > 0 && !lineWidgets[first])
first--;
this.firstRow = config.firstRow;
this.lastRow = config.lastRow;
renderer.$cursorLayer.config = config;
for (var i = first; i <= last; i++) {
var w = lineWidgets[i];
if (!w || !w.el) continue;
if (w.hidden) {
w.el.style.top = -100 - (w.pixelHeight || 0) + "px";
continue;
}
if (!w._inDocument) {
w._inDocument = true;
renderer.container.appendChild(w.el);
}
var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top;
if (!w.coverLine)
top += config.lineHeight * this.session.getRowLineCount(w.row);
w.el.style.top = top - config.offset + "px";
var left = w.coverGutter ? 0 : renderer.gutterWidth;
if (!w.fixedWidth)
left -= renderer.scrollLeft;
w.el.style.left = left + "px";
if (w.fullWidth && w.screenWidth) {
w.el.style.minWidth = config.width + 2 * config.padding + "px";
}
if (w.fixedWidth) {
w.el.style.right = renderer.scrollBar.getWidth() + "px";
} else {
w.el.style.right = "";
}
}
};
}).call(LineWidgets.prototype);
exports.LineWidgets = LineWidgets;
});
ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) {
"use strict";
var LineWidgets = acequire("../line_widgets").LineWidgets;
var dom = acequire("../lib/dom");
var Range = acequire("../range").Range;
function binarySearch(array, needle, comparator) {
var first = 0;
var last = array.length - 1;
while (first <= last) {
var mid = (first + last) >> 1;
var c = comparator(needle, array[mid]);
if (c > 0)
first = mid + 1;
else if (c < 0)
last = mid - 1;
else
return mid;
}
return -(first + 1);
}
function findAnnotations(session, row, dir) {
var annotations = session.getAnnotations().sort(Range.comparePoints);
if (!annotations.length)
return;
var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints);
if (i < 0)
i = -i - 1;
if (i >= annotations.length)
i = dir > 0 ? 0 : annotations.length - 1;
else if (i === 0 && dir < 0)
i = annotations.length - 1;
var annotation = annotations[i];
if (!annotation || !dir)
return;
if (annotation.row === row) {
do {
annotation = annotations[i += dir];
} while (annotation && annotation.row === row);
if (!annotation)
return annotations.slice();
}
var matched = [];
row = annotation.row;
do {
matched[dir < 0 ? "unshift" : "push"](annotation);
annotation = annotations[i += dir];
} while (annotation && annotation.row == row);
return matched.length && matched;
}
exports.showErrorMarker = function(editor, dir) {
var session = editor.session;
if (!session.widgetManager) {
session.widgetManager = new LineWidgets(session);
session.widgetManager.attach(editor);
}
var pos = editor.getCursorPosition();
var row = pos.row;
var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) {
return w.type == "errorMarker";
})[0];
if (oldWidget) {
oldWidget.destroy();
} else {
row -= dir;
}
var annotations = findAnnotations(session, row, dir);
var gutterAnno;
if (annotations) {
var annotation = annotations[0];
pos.column = (annotation.pos && typeof annotation.column != "number"
? annotation.pos.sc
: annotation.column) || 0;
pos.row = annotation.row;
gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row];
} else if (oldWidget) {
return;
} else {
gutterAnno = {
text: ["Looks good!"],
className: "ace_ok"
};
}
editor.session.unfold(pos.row);
editor.selection.moveToPosition(pos);
var w = {
row: pos.row,
fixedWidth: true,
coverGutter: true,
el: dom.createElement("div"),
type: "errorMarker"
};
var el = w.el.appendChild(dom.createElement("div"));
var arrow = w.el.appendChild(dom.createElement("div"));
arrow.className = "error_widget_arrow " + gutterAnno.className;
var left = editor.renderer.$cursorLayer
.getPixelPosition(pos).left;
arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px";
w.el.className = "error_widget_wrapper";
el.className = "error_widget " + gutterAnno.className;
el.innerHTML = gutterAnno.text.join("<br>");
el.appendChild(dom.createElement("div"));
var kb = function(_, hashId, keyString) {
if (hashId === 0 && (keyString === "esc" || keyString === "return")) {
w.destroy();
return {command: "null"};
}
};
w.destroy = function() {
if (editor.$mouseHandler.isMousePressed)
return;
editor.keyBinding.removeKeyboardHandler(kb);
session.widgetManager.removeLineWidget(w);
editor.off("changeSelection", w.destroy);
editor.off("changeSession", w.destroy);
editor.off("mouseup", w.destroy);
editor.off("change", w.destroy);
};
editor.keyBinding.addKeyboardHandler(kb);
editor.on("changeSelection", w.destroy);
editor.on("changeSession", w.destroy);
editor.on("mouseup", w.destroy);
editor.on("change", w.destroy);
editor.session.widgetManager.addLineWidget(w);
w.el.onmousedown = editor.focus.bind(editor);
editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight});
};
dom.importCssString("\
.error_widget_wrapper {\
background: inherit;\
color: inherit;\
border:none\
}\
.error_widget {\
border-top: solid 2px;\
border-bottom: solid 2px;\
margin: 5px 0;\
padding: 10px 40px;\
white-space: pre-wrap;\
}\
.error_widget.ace_error, .error_widget_arrow.ace_error{\
border-color: #ff5a5a\
}\
.error_widget.ace_warning, .error_widget_arrow.ace_warning{\
border-color: #F1D817\
}\
.error_widget.ace_info, .error_widget_arrow.ace_info{\
border-color: #5a5a5a\
}\
.error_widget.ace_ok, .error_widget_arrow.ace_ok{\
border-color: #5aaa5a\
}\
.error_widget_arrow {\
position: absolute;\
border: solid 5px;\
border-top-color: transparent!important;\
border-right-color: transparent!important;\
border-left-color: transparent!important;\
top: -5px;\
}\
", "");
});
ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) {
"use strict";
acequire("./lib/fixoldbrowsers");
var dom = acequire("./lib/dom");
var event = acequire("./lib/event");
var Editor = acequire("./editor").Editor;
var EditSession = acequire("./edit_session").EditSession;
var UndoManager = acequire("./undomanager").UndoManager;
var Renderer = acequire("./virtual_renderer").VirtualRenderer;
acequire("./worker/worker_client");
acequire("./keyboard/hash_handler");
acequire("./placeholder");
acequire("./multi_select");
acequire("./mode/folding/fold_mode");
acequire("./theme/textmate");
acequire("./ext/error_marker");
exports.config = acequire("./config");
exports.acequire = acequire;
if (true)
exports.define = __webpack_require__(34);
exports.edit = function(el) {
if (typeof el == "string") {
var _id = el;
el = document.getElementById(_id);
if (!el)
throw new Error("ace.edit can't find div #" + _id);
}
if (el && el.env && el.env.editor instanceof Editor)
return el.env.editor;
var value = "";
if (el && /input|textarea/i.test(el.tagName)) {
var oldNode = el;
value = oldNode.value;
el = dom.createElement("pre");
oldNode.parentNode.replaceChild(el, oldNode);
} else if (el) {
value = dom.getInnerText(el);
el.innerHTML = "";
}
var doc = exports.createEditSession(value);
var editor = new Editor(new Renderer(el));
editor.setSession(doc);
var env = {
document: doc,
editor: editor,
onResize: editor.resize.bind(editor, null)
};
if (oldNode) env.textarea = oldNode;
event.addListener(window, "resize", env.onResize);
editor.on("destroy", function() {
event.removeListener(window, "resize", env.onResize);
env.editor.container.env = null; // prevent memory leak on old ie
});
editor.container.env = editor.env = env;
return editor;
};
exports.createEditSession = function(text, mode) {
var doc = new EditSession(text, mode);
doc.setUndoManager(new UndoManager());
return doc;
}
exports.EditSession = EditSession;
exports.UndoManager = UndoManager;
exports.version = "1.2.6";
});
(function() {
ace.acequire(["ace/ace"], function(a) {
if (a) {
a.config.init(true);
a.define = ace.define;
}
if (!window.ace)
window.ace = a;
for (var key in a) if (a.hasOwnProperty(key))
window.ace[key] = a[key];
});
})();
module.exports = window.ace.acequire("ace/ace");
/***/ }),
/* 34 */
/***/ (function(module, exports) {
module.exports = function() {
throw new Error("define cannot be used indirect");
};
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
},
DocCommentHighlightRules.getTagRule(),
{
defaultToken : "comment.doc",
caseInsensitive: true
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getTagRule = function(start) {
return {
token : "comment.doc.tag.storage.type",
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
};
}
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var DocCommentHighlightRules = acequire("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules;
var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*";
var JavaScriptHighlightRules = function(options) {
var keywordMapper = this.createKeywordMapper({
"variable.language":
"Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors
"Namespace|QName|XML|XMLList|" + // E4X
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors
"SyntaxError|TypeError|URIError|" +
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions
"isNaN|parseFloat|parseInt|" +
"JSON|Math|" + // Other
"this|arguments|prototype|window|document" , // Pseudo
"keyword":
"const|yield|import|get|set|async|await|" +
"break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|of|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" +
"__parent__|__count__|escape|unescape|with|__proto__|" +
"class|enum|extends|super|export|implements|private|public|interface|package|protected|static",
"storage.type":
"const|let|var|function",
"constant.language":
"null|Infinity|NaN|undefined",
"support.function":
"alert",
"constant.language.boolean": "true|false"
}, "identifier");
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"u{[0-9a-fA-F]{1,6}}|" + // es6 unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-7][0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
this.$rules = {
"no_regex" : [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("no_regex"),
{
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, {
token : [
"storage.type", "punctuation.operator", "support.function",
"punctuation.operator", "entity.name.function", "text","keyword.operator"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "keyword.operator", "text", "storage.type",
"text", "paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"entity.name.function", "text", "punctuation.operator",
"text", "storage.type", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : [
"text", "text", "storage.type", "text", "paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "start"
}, {
token : ["support.constant"],
regex : /that\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/
}, {
token : keywordMapper,
regex : identifierRe
}, {
token : "punctuation.operator",
regex : /[.](?![.])/,
next : "property"
}, {
token : "keyword.operator",
regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/,
next : "start"
}, {
token : "punctuation.operator",
regex : /[?:,;.]/,
next : "start"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "start"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token: "comment",
regex: /^#!.*$/
}
],
property: [{
token : "text",
regex : "\\s+"
}, {
token : [
"storage.type", "punctuation.operator", "entity.name.function", "text",
"keyword.operator", "text",
"storage.type", "text", "entity.name.function", "text", "paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()",
next: "function_arguments"
}, {
token : "punctuation.operator",
regex : /[.](?![.])/
}, {
token : "support.function",
regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : "support.function.dom",
regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : "support.constant",
regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : "identifier",
regex : identifierRe
}, {
regex: "",
token: "empty",
next: "no_regex"
}
],
"start": [
DocCommentHighlightRules.getStartRule("doc-start"),
comments("start"),
{
token: "string.regexp",
regex: "\\/",
next: "regex"
}, {
token : "text",
regex : "\\s+|^$",
next : "start"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp",
regex: "/[sxngimy]*",
next: "no_regex"
}, {
token : "invalid",
regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/
}, {
token : "constant.language.escape",
regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/
}, {
token : "constant.language.delimiter",
regex: /\|/
}, {
token: "constant.language.escape",
regex: /\[\^?/,
next: "regex_character_class"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp"
}
],
"regex_character_class": [
{
token: "regexp.charclass.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "constant.language.escape",
regex: "]",
next: "regex"
}, {
token: "constant.language.escape",
regex: "-"
}, {
token: "empty",
regex: "$",
next: "no_regex"
}, {
defaultToken: "string.regexp.charachterclass"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe
}, {
token: "punctuation.operator",
regex: "[, ]+"
}, {
token: "punctuation.operator",
regex: "$"
}, {
token: "empty",
regex: "",
next: "no_regex"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qqstring"
}, {
token : "string",
regex : '"|$',
next : "no_regex"
}, {
defaultToken: "string"
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "\\\\$",
next : "qstring"
}, {
token : "string",
regex : "'|$",
next : "no_regex"
}, {
defaultToken: "string"
}
]
};
if (!options || !options.noES6) {
this.$rules.no_regex.unshift({
regex: "[{}]", onMatch: function(val, state, stack) {
this.next = val == "{" ? this.nextState : "";
if (val == "{" && stack.length) {
stack.unshift("start", state);
}
else if (val == "}" && stack.length) {
stack.shift();
this.next = stack.shift();
if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1)
return "paren.quasi.end";
}
return val == "{" ? "paren.lparen" : "paren.rparen";
},
nextState: "start"
}, {
token : "string.quasi.start",
regex : /`/,
push : [{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "paren.quasi.start",
regex : /\${/,
push : "start"
}, {
token : "string.quasi.end",
regex : /`/,
next : "pop"
}, {
defaultToken: "string.quasi"
}]
});
if (!options || options.jsx != false)
JSX.call(this);
}
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("no_regex") ]);
this.normalizeRules();
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
function JSX() {
var tagRegex = identifierRe.replace("\\d", "\\d\\-");
var jsxTag = {
onMatch : function(val, state, stack) {
var offset = val.charAt(1) == "/" ? 2 : 1;
if (offset == 1) {
if (state != this.nextState)
stack.unshift(this.next, this.nextState, 0);
else
stack.unshift(this.next);
stack[2]++;
} else if (offset == 2) {
if (state == this.nextState) {
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.shift();
stack.shift();
}
}
}
return [{
type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml",
value: val.slice(0, offset)
}, {
type: "meta.tag.tag-name.xml",
value: val.substr(offset)
}];
},
regex : "</?" + tagRegex + "",
next: "jsxAttributes",
nextState: "jsx"
};
this.$rules.start.unshift(jsxTag);
var jsxJsRule = {
regex: "{",
token: "paren.quasi.start",
push: "start"
};
this.$rules.jsx = [
jsxJsRule,
jsxTag,
{include : "reference"},
{defaultToken: "string"}
];
this.$rules.jsxAttributes = [{
token : "meta.tag.punctuation.tag-close.xml",
regex : "/?>",
onMatch : function(value, currentState, stack) {
if (currentState == stack[0])
stack.shift();
if (value.length == 2) {
if (stack[0] == this.nextState)
stack[1]--;
if (!stack[1] || stack[1] < 0) {
stack.splice(0, 2);
}
}
this.next = stack[0] || "start";
return [{type: this.token, value: value}];
},
nextState: "jsx"
},
jsxJsRule,
comments("jsxAttributes"),
{
token : "entity.other.attribute-name.xml",
regex : tagRegex
}, {
token : "keyword.operator.attribute-equals.xml",
regex : "="
}, {
token : "text.tag-whitespace.xml",
regex : "\\s+"
}, {
token : "string.attribute-value.xml",
regex : "'",
stateName : "jsx_attr_q",
push : [
{token : "string.attribute-value.xml", regex: "'", next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
}, {
token : "string.attribute-value.xml",
regex : '"',
stateName : "jsx_attr_qq",
push : [
{token : "string.attribute-value.xml", regex: '"', next: "pop"},
{include : "reference"},
{defaultToken : "string.attribute-value.xml"}
]
},
jsxTag
];
this.$rules.reference = [{
token : "constant.language.escape.reference.xml",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}];
}
function comments(next) {
return [
{
token : "comment", // multi line comment
regex : /\/\*/,
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "\\*\\/", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}, {
token : "comment",
regex : "\\/\\/",
next: [
DocCommentHighlightRules.getTagRule(),
{token : "comment", regex : "$|^", next : next || "pop"},
{defaultToken : "comment", caseInsensitive: true}
]
}
];
}
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) {
"use strict";
var Range = acequire("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../../lib/oop");
var Range = acequire("../../range").Range;
var BaseFoldMode = acequire("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(acequire, exports, module) {
"use strict";
var oop = acequire("../lib/oop");
var TextMode = acequire("./text").Mode;
var JavaScriptHighlightRules = acequire("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = acequire("../worker/worker_client").WorkerClient;
var CstyleBehaviour = acequire("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = acequire("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = JavaScriptHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "no_regex") {
var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || endState == "no_regex") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], __webpack_require__(48), "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(results) {
session.setAnnotations(results.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/javascript";
}).call(Mode.prototype);
exports.Mode = Mode;
});
/***/ }),
/* 36 */
/***/ (function(module, exports) {
ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-monokai";
exports.cssText = ".ace-monokai .ace_gutter {\
background: #2F3129;\
color: #8F908A\
}\
.ace-monokai .ace_print-margin {\
width: 1px;\
background: #555651\
}\
.ace-monokai {\
background-color: #272822;\
color: #F8F8F2\
}\
.ace-monokai .ace_cursor {\
color: #F8F8F0\
}\
.ace-monokai .ace_marker-layer .ace_selection {\
background: #49483E\
}\
.ace-monokai.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px #272822;\
}\
.ace-monokai .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0)\
}\
.ace-monokai .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #49483E\
}\
.ace-monokai .ace_marker-layer .ace_active-line {\
background: #202020\
}\
.ace-monokai .ace_gutter-active-line {\
background-color: #272727\
}\
.ace-monokai .ace_marker-layer .ace_selected-word {\
border: 1px solid #49483E\
}\
.ace-monokai .ace_invisible {\
color: #52524d\
}\
.ace-monokai .ace_entity.ace_name.ace_tag,\
.ace-monokai .ace_keyword,\
.ace-monokai .ace_meta.ace_tag,\
.ace-monokai .ace_storage {\
color: #F92672\
}\
.ace-monokai .ace_punctuation,\
.ace-monokai .ace_punctuation.ace_tag {\
color: #fff\
}\
.ace-monokai .ace_constant.ace_character,\
.ace-monokai .ace_constant.ace_language,\
.ace-monokai .ace_constant.ace_numeric,\
.ace-monokai .ace_constant.ace_other {\
color: #AE81FF\
}\
.ace-monokai .ace_invalid {\
color: #F8F8F0;\
background-color: #F92672\
}\
.ace-monokai .ace_invalid.ace_deprecated {\
color: #F8F8F0;\
background-color: #AE81FF\
}\
.ace-monokai .ace_support.ace_constant,\
.ace-monokai .ace_support.ace_function {\
color: #66D9EF\
}\
.ace-monokai .ace_fold {\
background-color: #A6E22E;\
border-color: #F8F8F2\
}\
.ace-monokai .ace_storage.ace_type,\
.ace-monokai .ace_support.ace_class,\
.ace-monokai .ace_support.ace_type {\
font-style: italic;\
color: #66D9EF\
}\
.ace-monokai .ace_entity.ace_name.ace_function,\
.ace-monokai .ace_entity.ace_other,\
.ace-monokai .ace_entity.ace_other.ace_attribute-name,\
.ace-monokai .ace_variable {\
color: #A6E22E\
}\
.ace-monokai .ace_variable.ace_parameter {\
font-style: italic;\
color: #FD971F\
}\
.ace-monokai .ace_string {\
color: #E6DB74\
}\
.ace-monokai .ace_comment {\
color: #75715E\
}\
.ace-monokai .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\
}";
var dom = acequire("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
/***/ }),
/* 37 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return gameOptionsBoxOpen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return gameOptionsBoxClose; });
/* GameOptions.js */
//Close box when clicking outside
$(document).click(function(event) {
if (gameOptionsOpened) {
if ( $(event.target).closest(".game-options-box").get(0) == null ) {
gameOptionsBoxClose();
}
}
});
var gameOptionsOpened = false;
function gameOptionsBoxInit() {
//Menu link button
document.getElementById("options-menu-link").addEventListener("click", function() {
gameOptionsBoxOpen();
return false;
});
//Close button
var closeButton = document.getElementById("game-options-close-button");
closeButton.addEventListener("click", function() {
gameOptionsBoxClose();
return false;
});
};
document.addEventListener("DOMContentLoaded", gameOptionsBoxInit, false);
function gameOptionsBoxClose() {
gameOptionsOpened = false;
var box = document.getElementById("game-options-container");
box.style.display = "none";
}
function gameOptionsBoxOpen() {
var box = document.getElementById("game-options-container");
box.style.display = "block";
setTimeout(function() {
gameOptionsOpened = true;
}, 500);
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! @preserve
* numeral.js
* version : 2.0.6
* author : Adam Draper
* license : MIT
* http://adamwdraper.github.com/Numeral-js/
*/
!function(a,b){ true?!(__WEBPACK_AMD_DEFINE_FACTORY__ = (b),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)):"object"==typeof module&&module.exports?module.exports=b():a.numeral=b()}(this,function(){function a(a,b){this._input=a,this._value=b}var b,c,d="2.0.6",e={},f={},g={currentLocale:"en",zeroFormat:null,nullFormat:null,defaultFormat:"0,0",scalePercentBy100:!0},h={currentLocale:g.currentLocale,zeroFormat:g.zeroFormat,nullFormat:g.nullFormat,defaultFormat:g.defaultFormat,scalePercentBy100:g.scalePercentBy100};return b=function(d){var f,g,i,j;if(b.isNumeral(d))f=d.value();else if(0===d||"undefined"==typeof d)f=0;else if(null===d||c.isNaN(d))f=null;else if("string"==typeof d)if(h.zeroFormat&&d===h.zeroFormat)f=0;else if(h.nullFormat&&d===h.nullFormat||!d.replace(/[^0-9]+/g,"").length)f=null;else{for(g in e)if(j="function"==typeof e[g].regexps.unformat?e[g].regexps.unformat():e[g].regexps.unformat,j&&d.match(j)){i=e[g].unformat;break}i=i||b._.stringToNumber,f=i(d)}else f=Number(d)||null;return new a(d,f)},b.version=d,b.isNumeral=function(b){return b instanceof a},b._=c={numberToFormat:function(a,c,d){var e,g,h,i,j,k,l,m=f[b.options.currentLocale],n=!1,o=!1,p=0,q="",r=1e12,s=1e9,t=1e6,u=1e3,v="",w=!1;if(a=a||0,g=Math.abs(a),b._.includes(c,"(")?(n=!0,c=c.replace(/[\(|\)]/g,"")):(b._.includes(c,"+")||b._.includes(c,"-"))&&(j=b._.includes(c,"+")?c.indexOf("+"):0>a?c.indexOf("-"):-1,c=c.replace(/[\+|\-]/g,"")),b._.includes(c,"a")&&(e=c.match(/a(k|m|b|t)?/),e=e?e[1]:!1,b._.includes(c," a")&&(q=" "),c=c.replace(new RegExp(q+"a[kmbt]?"),""),g>=r&&!e||"t"===e?(q+=m.abbreviations.trillion,a/=r):r>g&&g>=s&&!e||"b"===e?(q+=m.abbreviations.billion,a/=s):s>g&&g>=t&&!e||"m"===e?(q+=m.abbreviations.million,a/=t):(t>g&&g>=u&&!e||"k"===e)&&(q+=m.abbreviations.thousand,a/=u)),b._.includes(c,"[.]")&&(o=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],k=c.indexOf(","),p=(c.split(".")[0].split(",")[0].match(/0/g)||[]).length,i?(b._.includes(i,"[")?(i=i.replace("]",""),i=i.split("["),v=b._.toFixed(a,i[0].length+i[1].length,d,i[1].length)):v=b._.toFixed(a,i.length,d),h=v.split(".")[0],v=b._.includes(v,".")?m.delimiters.decimal+v.split(".")[1]:"",o&&0===Number(v.slice(1))&&(v="")):h=b._.toFixed(a,0,d),q&&!e&&Number(h)>=1e3&&q!==m.abbreviations.trillion)switch(h=String(Number(h)/1e3),q){case m.abbreviations.thousand:q=m.abbreviations.million;break;case m.abbreviations.million:q=m.abbreviations.billion;break;case m.abbreviations.billion:q=m.abbreviations.trillion}if(b._.includes(h,"-")&&(h=h.slice(1),w=!0),h.length<p)for(var x=p-h.length;x>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<i.before.length;g++)switch(f=i.before[g]){case"$":e=b._.insert(e,h.currency.symbol,g);break;case" ":e=b._.insert(e," ",g+h.currency.symbol.length-1)}for(g=i.after.length-1;g>=0;g--)switch(f=i.after[g]){case"$":e=g===i.after.length-1?e+h.currency.symbol:b._.insert(e,h.currency.symbol,-(i.after.length-(1+g)));break;case" ":e=g===i.after.length-1?e+" ":b._.insert(e," ",-(i.after.length-(1+g)+h.currency.symbol.length-1))}return e}})}(),function(){b.register("format","exponential",{regexps:{format:/(e\+|e-)/,unformat:/(e\+|e-)/},format:function(a,c,d){var e,f="number"!=typeof a||b._.isNaN(a)?"0e+0":a.toExponential(),g=f.split("e");return c=c.replace(/e[\+|\-]{1}0/,""),e=b._.numberToFormat(Number(g[0]),c,d),e+"e"+g[1]},unformat:function(a){function c(a,c,d,e){var f=b._.correctionFactor(a,c),g=a*f*(c*f)/(f*f);return g}var d=b._.includes(a,"e+")?a.split("e+"):a.split("e-"),e=Number(d[0]),f=Number(d[1]);return f=b._.includes(a,"e-")?f*=-1:f,b._.reduce([e,Math.pow(10,f)],c,1)}})}(),function(){b.register("format","ordinal",{regexps:{format:/(o)/},format:function(a,c,d){var e,f=b.locales[b.options.currentLocale],g=b._.includes(c," o")?" ":"";return c=c.replace(/\s?o/,""),g+=f.ordinal(a),e=b._.numberToFormat(a,c,d),e+g}})}(),function(){b.register("format","percentage",{regexps:{format:/(%)/,unformat:/(%)/},format:function(a,c,d){var e,f=b._.includes(c," %")?" ":"";return b.options.scalePercentBy100&&(a=100*a),c=c.replace(/\s?\%/,""),e=b._.numberToFormat(a,c,d),b._.includes(e,")")?(e=e.split(""),e.splice(-1,0,f+"%"),e=e.join("")):e=e+f+"%",e},unformat:function(a){var c=b._.stringToNumber(a);return b.options.scalePercentBy100?.01*c:c}})}(),function(){b.register("format","time",{regexps:{format:/(:)/,unformat:/(:)/},format:function(a,b,c){var d=Math.floor(a/60/60),e=Math.floor((a-60*d*60)/60),f=Math.round(a-60*d*60-60*e);return d+":"+(10>e?"0"+e:e)+":"+(10>f?"0"+f:f)},unformat:function(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}})}(),b});
/***/ }),
/* 39 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return NetscriptFunctions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return initSingularitySFFlags; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hasSingularitySF; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__ = __webpack_require__(42);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__HacknetNode_js__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Location_js__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__Terminal_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__ = __webpack_require__(45);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__NetscriptEnvironment_js__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__utils_IPAddress_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__ = __webpack_require__(5);
var hasSingularitySF = false;
var singularitySFLvl = 1;
function initSingularitySFFlags() {
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].sourceFiles.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].sourceFiles[i].n === 4) {
hasSingularitySF = true;
singularitySFLvl = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].sourceFiles[i].lvl;
}
}
}
function NetscriptFunctions(workerScript) {
return {
hacknetnodes : __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacknetNodes,
scan : function(ip=workerScript.serverIp){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, 'Invalid IP or hostname passed into scan() command');
}
var out = [];
for (var i = 0; i < server.serversOnNetwork.length; i++) {
var entry = server.getServerOnNetwork(i).hostname;
if (entry == null) {
continue;
}
out.push(entry);
}
workerScript.scriptRef.log('scan() returned ' + server.serversOnNetwork.length + ' connections for ' + server.hostname);
return out;
},
hack : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "hack() error. Invalid IP or hostname passed in: " + ip + ". Stopping...");
}
//Calculate the hacking time
var hackingTime = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["i" /* 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(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user does not have root access");
}
if (server.requiredHackingSkill > __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill) {
workerScript.scriptRef.log("Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot hack this server (" + server.hostname + ") because user's hacking skill is not high enough");
}
workerScript.scriptRef.log("Attempting to hack " + ip + " in " + hackingTime.toFixed(3) + " seconds (t=" + threads + ")");
//console.log("Hacking " + server.hostname + " after " + hackingTime.toString() + " seconds (t=" + threads + ")");
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["d" /* netscriptDelay */])(hackingTime* 1000).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
var hackChance = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["h" /* scriptCalculateHackingChance */])(server);
var rand = Math.random();
var expGainedOnSuccess = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["f" /* scriptCalculateExpGain */])(server) * threads;
var expGainedOnFailure = (expGainedOnSuccess / 4);
if (rand < hackChance) { //Success!
var moneyGained = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["j" /* 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;}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainMoney(moneyGained);
workerScript.scriptRef.onlineMoneyMade += moneyGained;
workerScript.scriptRef.recordHack(server.ip, moneyGained, threads);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainHackingExp(expGainedOnSuccess);
workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
//console.log("Script successfully hacked " + server.hostname + " for $" + formatNumber(moneyGained, 2) + " and " + formatNumber(expGainedOnSuccess, 4) + " exp");
workerScript.scriptRef.log("Script SUCCESSFULLY hacked " + server.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(moneyGained, 2) + " and " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnSuccess, 4) + " exp (t=" + threads + ")");
server.fortify(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ServerFortifyAmount * threads);
return Promise.resolve(true);
} else {
//Player only gains 25% exp for failure? TODO Can change this later to balance
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainHackingExp(expGainedOnFailure);
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
//console.log("Script unsuccessful to hack " + server.hostname + ". Gained " + formatNumber(expGainedOnFailure, 4) + " exp");
workerScript.scriptRef.log("Script FAILED to hack " + server.hostname + ". Gained " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGainedOnFailure, 4) + " exp (t=" + threads + ")");
return Promise.resolve(false);
}
});
},
sleep : function(time,log=true){
if (time === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "sleep() call has incorrect number of arguments. Takes 1 argument");
}
if (log) {
workerScript.scriptRef.log("Sleeping for " + time + " milliseconds");
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["d" /* netscriptDelay */])(time).then(function() {
return Promise.resolve(true);
});
},
grow : function(ip){
var threads = workerScript.scriptRef.threads;
if (isNaN(threads) || threads < 1) {threads = 1;}
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "grow() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot grow(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot grow this server (" + server.hostname + ") because user does not have root access");
}
var growTime = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["g" /* scriptCalculateGrowTime */])(server);
//console.log("Executing grow() on server " + server.hostname + " in " + formatNumber(growTime/1000, 3) + " seconds")
workerScript.scriptRef.log("Executing grow() on server " + server.hostname + " in " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growTime/1000, 3) + " seconds (t=" + threads + ")");
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["d" /* netscriptDelay */])(growTime).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
server.moneyAvailable += (1 * threads); //It can be grown even if it has no money
var growthPercentage = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["j" /* processSingleServerGrowth */])(server, 450 * threads);
workerScript.scriptRef.recordGrow(server.ip, threads);
var expGain = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["f" /* scriptCalculateExpGain */])(server) * threads;
if (growthPercentage == 1) {
expGain = 0;
}
workerScript.scriptRef.log("Available money on " + server.hostname + " grown by "
+ Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(growthPercentage*100 - 100, 6) + "%. Gained " +
Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads +")");
workerScript.scriptRef.onlineExpGained += expGain;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainHackingExp(expGain);
return Promise.resolve(growthPercentage);
});
},
weaken : function(ip){
var threads = workerScript.scriptRef.threads;
if (isNaN(threads) || threads < 1) {threads = 1;}
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "weaken() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot weaken(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot weaken this server (" + server.hostname + ") because user does not have root access");
}
var weakenTime = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["k" /* scriptCalculateWeakenTime */])(server);
//console.log("Executing weaken() on server " + server.hostname + " in " + formatNumber(weakenTime/1000, 3) + " seconds")
workerScript.scriptRef.log("Executing weaken() on server " + server.hostname + " in " +
Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(weakenTime/1000, 3) + " seconds (t=" + threads + ")");
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["d" /* netscriptDelay */])(weakenTime).then(function() {
if (workerScript.env.stopFlag) {return Promise.reject(workerScript);}
server.weaken(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads);
workerScript.scriptRef.recordWeaken(server.ip, threads);
var expGain = Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["f" /* scriptCalculateExpGain */])(server) * threads;
workerScript.scriptRef.log("Server security level on " + server.hostname + " weakened to " + server.hackDifficulty +
". Gained " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(expGain, 4) + " hacking exp (t=" + threads + ")");
workerScript.scriptRef.onlineExpGained += expGain;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainHackingExp(expGain);
return Promise.resolve(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ServerWeakenAmount * threads);
});
},
print : function(args){
if (args === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "print() call has incorrect number of arguments. Takes 1 argument");
}
workerScript.scriptRef.log(args.toString());
},
tprint : function(args) {
if (args === undefined || args === null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "tprint() call has incorrect number of arguments. Takes 1 argument");
}
Object(__WEBPACK_IMPORTED_MODULE_15__Terminal_js__["b" /* post */])(workerScript.scriptRef.filename + ": " + args.toString());
},
clearLog : function() {
workerScript.scriptRef.clearLog();
},
nuke : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call nuke(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].NukeProgram)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Not enough ports opened to use NUKE.exe virus");
}
if (server.hasAdminRights) {
workerScript.scriptRef.log("Already have root access to " + server.hostname);
} else {
server.hasAdminRights = true;
workerScript.scriptRef.log("Executed NUKE.exe virus on " + server.hostname + " to gain root access");
}
return true;
},
brutessh : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call brutessh(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].BruteSSHProgram)) {
workerScript.scriptRef.log("You do not have the BruteSSH.exe program!");
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the BruteSSH.exe program!");
}
if (!server.sshPortOpen) {
workerScript.scriptRef.log("Executed BruteSSH.exe on " + server.hostname + " to open SSH port (22)");
server.sshPortOpen = true;
++server.openPortCount;
} else {
workerScript.scriptRef.log("SSH Port (22) already opened on " + server.hostname);
}
return true;
},
ftpcrack : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call ftpcrack(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].FTPCrackProgram)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the FTPCrack.exe program!");
}
if (!server.ftpPortOpen) {
workerScript.scriptRef.log("Executed FTPCrack.exe on " + server.hostname + " to open FTP port (21)");
server.ftpPortOpen = true;
++server.openPortCount;
} else {
workerScript.scriptRef.log("FTP Port (21) already opened on " + server.hostname);
}
return true;
},
relaysmtp : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call relaysmtp(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the relaySMTP.exe program!");
}
if (!server.smtpPortOpen) {
workerScript.scriptRef.log("Executed relaySMTP.exe on " + server.hostname + " to open SMTP port (25)");
server.smtpPortOpen = true;
++server.openPortCount;
} else {
workerScript.scriptRef.log("SMTP Port (25) already opened on " + server.hostname);
}
return true;
},
httpworm : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call httpworm(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].HTTPWormProgram)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the HTTPWorm.exe program!");
}
if (!server.httpPortOpen) {
workerScript.scriptRef.log("Executed HTTPWorm.exe on " + server.hostname + " to open HTTP port (80)");
server.httpPortOpen = true;
++server.openPortCount;
} else {
workerScript.scriptRef.log("HTTP Port (80) already opened on " + server.hostname);
}
return true;
},
sqlinject : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Program call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot call sqlinject(). Invalid IP or hostname passed in: " + ip);
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasProgram(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].SQLInjectProgram)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You do not have the SQLInject.exe program!");
}
if (!server.sqlPortOpen) {
workerScript.scriptRef.log("Executed SQLInject.exe on " + server.hostname + " to open SQL port (1433)");
server.sqlPortOpen = true;
++server.openPortCount;
} else {
workerScript.scriptRef.log("SQL Port (1433) already opened on " + server.hostname);
}
return true;
},
run : function(scriptname,threads = 1){
if (scriptname === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "run() call has incorrect number of arguments. Usage: run(scriptname, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["e" /* runScriptFromScript */])(scriptServer, scriptname, argsForNewScript, workerScript, threads);
},
exec : function(scriptname,ip,threads = 1){
if (scriptname === undefined || ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "exec() call has incorrect number of arguments. Usage: exec(scriptname, server, [numThreads], [arg1], [arg2]...)");
}
if (isNaN(threads) || threads < 1) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid hostname/ip passed into exec() command: " + ip);
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["e" /* runScriptFromScript */])(server, scriptname, argsForNewScript, workerScript, threads);
},
kill : function(filename,ip){
if (filename === undefined || ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "kill() call has incorrect number of arguments. Usage: kill(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("kill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_10__Script_js__["d" /* findRunningScript */])(filename, argsForKillTarget, server);
if (runningScriptObj == null) {
workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_20__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget));
return false;
}
var res = Object(__WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__["d" /* killWorkerScript */])(runningScriptObj, server.ip);
if (res) {
workerScript.scriptRef.log("Killing " + filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_20__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget) + ". May take up to a few minutes for the scripts to die...");
return true;
} else {
workerScript.scriptRef.log("kill() failed. No such script "+ filename + " on " + server.hostname + " with args: " + Object(__WEBPACK_IMPORTED_MODULE_20__utils_HelperFunctions_js__["f" /* printArray */])(argsForKillTarget));
return false;
}
},
killall : function(ip){
if (ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "killall() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("killall() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "killall() failed. Invalid IP or hostname passed in: " + ip);
}
for (var i = server.runningScripts.length-1; i >= 0; --i) {
Object(__WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip);
}
workerScript.scriptRef.log("killall(): Killing all scripts on " + server.hostname + ". May take a few minutes for the scripts to die");
return true;
},
scp : function(scriptname,ip){
if (scriptname === undefined || ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "scp() call has incorrect number of arguments. Takes 2 arguments");
}
var destServer = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (destServer == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid hostname/ip passed into scp() command: " + ip);
}
var currServ = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(workerScript.serverIp);
if (currServ == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server ip for this script. This is a bug please contact game developer");
}
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) {
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 __WEBPACK_IMPORTED_MODULE_10__Script_js__["c" /* Script */]();
newScript.filename = scriptname;
newScript.code = sourceScript.code;
newScript.ramUsage = sourceScript.ramUsage;
newScript.server = destServer.ip;
destServer.scripts.push(newScript);
workerScript.scriptRef.log(scriptname + " copied over to " + destServer.hostname);
return true;
},
hasRootAccess : function(ip){
if (ip===undefined){
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() call has incorrect number of arguments. Takes 1 argument");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null){
workerScript.scriptRef.log("hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "hasRootAccess() failed. Invalid IP or hostname passed in: " + ip);
}
return server.hasAdminRights;
},
getHostname : function(){
var scriptServer = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(workerScript.serverIp);
if (scriptServer == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Could not find server. This is a bug in the game. Report to game dev");
}
return scriptServer.hostname;
},
getHackingLevel : function(){
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].updateSkillLevels();
workerScript.scriptRef.log("getHackingLevel() returned " + __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill);
return __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill;
},
getServerMoneyAvailable : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("Cannot getServerMoneyAvailable(). Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot getServerMoneyAvailable(). Invalid IP or hostname passed in: " + ip);
}
if (server.hostname == "home") {
//Return player's money
workerScript.scriptRef.log("getServerMoneyAvailable('home') returned player's money: $" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.toNumber(), 2));
return __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.toNumber();
}
workerScript.scriptRef.log("getServerMoneyAvailable() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyAvailable, 2) + " for " + server.hostname);
return server.moneyAvailable;
},
getServerSecurityLevel : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.hackDifficulty, 3) + " for " + server.hostname);
return server.hackDifficulty;
},
getServerBaseSecurityLevel : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerBaseSecurityLevel() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerBaseSecurityLevel() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.baseDifficulty, 3) + " for " + server.hostname);
return server.baseDifficulty;
},
getServerRequiredHackingLevel : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerRequiredHackingLevel() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerRequiredHackingLevel returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.requiredHackingSkill, 0) + " for " + server.hostname);
return server.requiredHackingSkill;
},
getServerMaxMoney : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerMaxMoney() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerMaxMoney() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.moneyMax, 0) + " for " + server.hostname);
return server.moneyMax;
},
getServerGrowth : function(ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerGrowth() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerGrowth() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.serverGrowth, 0) + " for " + server.hostname);
return server.serverGrowth;
},
getServerNumPortsRequired : function(ip){
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerNumPortsRequired() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerNumPortsRequired() returned " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.numOpenPortsRequired, 0) + " for " + server.hostname);
return server.numOpenPortsRequired;
},
getServerRam : function(ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getServerRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getServerRam() failed. Invalid IP or hostname passed in: " + ip);
}
workerScript.scriptRef.log("getServerRam() returned [" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.maxRam, 2) + "GB, " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(server.ramUsed, 2) + "GB]");
return [server.maxRam, server.ramUsed];
},
fileExists : function(filename,ip=workerScript.serverIp){
if (filename === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "fileExists() call has incorrect number of arguments. Usage: fileExists(scriptname, [server])");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("fileExists() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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;
}
}
return false;
},
isRunning : function(filename,ip){
if (filename === undefined || ip === undefined) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "isRunning() call has incorrect number of arguments. Usage: isRunning(scriptname, server, [arg1], [arg2]...)");
}
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("isRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_10__Script_js__["d" /* findRunningScript */])(filename, argsForTargetScript, server) != null);
},
getNextHacknetNodeCost : __WEBPACK_IMPORTED_MODULE_7__HacknetNode_js__["b" /* getCostOfNextHacknetNode */],
purchaseHacknetNode : __WEBPACK_IMPORTED_MODULE_7__HacknetNode_js__["d" /* purchaseHacknet */],
getStockPrice : function(symbol) {
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasTixApiAccess) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPrice()");
}
var stock = __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["b" /* SymbolToStockMap */][symbol];
if (stock == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()");
}
return parseFloat(stock.price.toFixed(3));
},
getStockPosition : function(symbol) {
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasTixApiAccess) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use getStockPosition()");
}
var stock = __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["b" /* SymbolToStockMap */][symbol];
if (stock == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()");
}
return [stock.playerShares, stock.playerAvgPx];
},
buyStock : function(symbol, shares) {
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasTixApiAccess) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use buyStock()");
}
var stock = __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["b" /* SymbolToStockMap */][symbol];
if (stock == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()");
}
if (shares == 0) {return false;}
if (stock == null || shares < 0 || isNaN(shares)) {
workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to buyStock()");
return false;
}
shares = Math.round(shares);
var totalPrice = stock.price * shares;
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.lt(totalPrice + __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].StockMarketCommission)) {
workerScript.scriptRef.log("Not enough money to purchase " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " +
symbol + ". Need $" +
Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalPrice + __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].StockMarketCommission, 2).toString());
return false;
}
var origTotal = stock.playerShares * stock.playerAvgPx;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(totalPrice + __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].StockMarketCommission);
var newTotal = origTotal + totalPrice;
stock.playerShares += shares;
stock.playerAvgPx = newTotal / stock.playerShares;
if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].Page.StockMarket) {
Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["j" /* updateStockPlayerPosition */])(stock);
}
workerScript.scriptRef.log("Bought " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share");
return true;
},
sellStock : function(symbol, shares) {
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hasTixApiAccess) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "You don't have TIX API Access! Cannot use sellStock()");
}
var stock = __WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["b" /* SymbolToStockMap */][symbol];
if (stock == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid stock symbol passed into getStockPrice()");
}
if (shares == 0) {return false;}
if (stock == null || shares < 0 || isNaN(shares)) {
workerScript.scriptRef.log("Error: Invalid 'shares' argument passed to sellStock()");
return false;
}
if (shares > stock.playerShares) {shares = stock.playerShares;}
if (shares == 0) {return false;}
var gains = stock.price * shares - __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].StockMarketCommission;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].gainMoney(gains);
//Calculate net profit and add to script stats
var netProfit = ((stock.price - stock.playerAvgPx) * shares) - __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].StockMarketCommission;
if (isNaN(netProfit)) {netProfit = 0;}
workerScript.scriptRef.onlineMoneyMade += netProfit;
stock.playerShares -= shares;
if (stock.playerShares == 0) {
stock.playerAvgPx = 0;
}
if (__WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].currentPage == __WEBPACK_IMPORTED_MODULE_5__engine_js__["Engine"].Page.StockMarket) {
Object(__WEBPACK_IMPORTED_MODULE_14__StockMarket_js__["j" /* updateStockPlayerPosition */])(stock);
}
workerScript.scriptRef.log("Sold " + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(shares, 0) + " shares of " + stock.symbol + " at $" +
Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stock.price, 2) + " per share. Gained " +
"$" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(gains, 2));
return true;
},
purchaseServer : function(hostname, ram) {
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s\s+/g, '');
if (hostnameStr == "") {
workerScript.scriptRef.log("Error: Passed empty string for hostname argument of purchaseServer()");
return "";
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) {
workerScript.scriptRef.log("Error: You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit +
" servers. You cannot purchase any more.");
return "";
}
ram = Math.round(ram);
if (isNaN(ram) || !Object(__WEBPACK_IMPORTED_MODULE_20__utils_HelperFunctions_js__["e" /* powerOfTwo */])(ram)) {
workerScript.scriptRef.log("Error: Invalid ram argument passed to purchaseServer(). Must be numeric and a power of 2");
return "";
}
var cost = ram * __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamServer;
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.lt(cost)) {
workerScript.scriptRef.log("Error: Not enough money to purchase server. Need $" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2));
return "";
}
var newServ = new __WEBPACK_IMPORTED_MODULE_11__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_21__utils_IPAddress_js__["a" /* createRandomIp */])(), hostnameStr, "", false, true, true, ram);
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["a" /* AddToAllServers */])(newServ);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip);
var homeComputer = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(cost);
workerScript.scriptRef.log("Purchased new server with hostname " + newServ.hostname + " for $" + Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["c" /* formatNumber */])(cost, 2));
return newServ.hostname;
},
deleteServer : function(hostname) {
var hostnameStr = String(hostname);
hostnameStr = hostnameStr.replace(/\s\s+/g, '');
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["c" /* 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;
//A server cannot delete itself
if (ip == workerScript.serverIp) {
workerScript.scriptRef.log("Error: Cannot call deleteServer() on self. Function 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 < __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].purchasedServers.length; ++i) {
if (ip == __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].purchasedServers[i]) {
found = true;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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 __WEBPACK_IMPORTED_MODULE_11__Server_js__["b" /* AllServers */][ip];
//Delete from home computer
found = false;
var homeComputer = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer();
for (var i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (ip == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1);
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;
},
round : function(n) {
if (isNaN(n)) {return 0;}
return Math.round(n);
},
write : function(port, data="") {
if (!isNaN(port)) {
//Port 1-10
if (port < 1 || port > 10) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid.");
}
var portName = "Port" + String(port);
var port = __WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__["a" /* NetscriptPorts */][portName];
if (port == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
port.push(data);
if (port.length > __WEBPACK_IMPORTED_MODULE_12__Settings_js__["a" /* Settings */].MaxPortCapacity) {
port.shift();
return true;
}
return false;
} else {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10");
}
},
read : function(port) {
if (!isNaN(port)) {
//Port 1-10
if (port < 1 || port > 10) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Trying to write to invalid port: " + port + ". Only ports 1-10 are valid.");
}
var portName = "Port" + String(port);
var port = __WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__["a" /* NetscriptPorts */][portName];
if (port == null) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Could not find port: " + port + ". This is a bug contact the game developer");
}
if (port.length == 0) {
return "NULL PORT DATA";
} else {
return port.shift();
}
} else {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Invalid argument passed in for port: " + port + ". Must be a number between 1 and 10");
}
},
scriptRunning : function(scriptname, ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptRunning() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("scriptKill() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_16__NetscriptWorker_js__["d" /* killWorkerScript */])(server.runningScripts[i], server.ip);
suc = true;
}
}
return suc;
},
getScriptRam : function (scriptname, ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getScriptRam() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getHackTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getHackTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["i" /* scriptCalculateHackingTime */])(server); //Returns seconds
},
getGrowTime : function(ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getGrowTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["g" /* scriptCalculateGrowTime */])(server) / 1000; //Returns seconds
},
getWeakenTime : function(ip) {
var server = Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["e" /* getServer */])(ip);
if (server == null) {
workerScript.scriptRef.log("getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "getWeakenTime() failed. Invalid IP or hostname passed in: " + ip);
}
return Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["k" /* scriptCalculateWeakenTime */])(server) / 1000; //Returns seconds
},
/* Singularity Functions */
universityCourse(universityName, className) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run universityCourse(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].isWorking) {
var txt = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].singularityStopWork();
workerScript.scriptRef.log(txt);
}
var costMult, expMult;
switch(universityName.toLowerCase()) {
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].AevumSummitUniversity.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot study at Summit University because you are not in Aevum. universityCourse() failed");
return false;
}
costMult = 4;
expMult = 3;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12RothmanUniversity.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot study at Rothman University because you are not in Sector-12. universityCourse() failed");
return false;
}
costMult = 3;
expMult = 2;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].VolhavenZBInstituteOfTechnology.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Volhaven) {
workerScript.scriptRef.log("ERROR: You cannot study at ZB Institute of Technology because you are not in Volhaven. universityCourse() failed");
return false;
}
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 = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassStudyComputerScience;
break;
case "Data Structures".toLowerCase():
task = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassDataStructures;
break;
case "Networks".toLowerCase():
task = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassNetworks;
break;
case "Algorithms".toLowerCase():
task = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassAlgorithms;
break;
case "Management".toLowerCase():
task = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassManagement;
break;
case "Leadership".toLowerCase():
task = __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassLeadership;
break;
default:
workerScript.scriptRef.log("Invalid class name: " + className + ". universityCourse() failed");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startClass(costMult, expMult, task);
workerScript.scriptRef.log("Started " + task + " at " + universityName);
return true;
},
gymWorkout(gymName, stat) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run gymWorkout(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].isWorking) {
var txt = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].singularityStopWork();
workerScript.scriptRef.log(txt);
}
var costMult, expMult;
switch(gymName.toLowerCase()) {
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].AevumCrushFitnessGym.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot workout at Crush Fitness because you are not in Aevum. gymWorkout() failed");
return false;
}
costMult = 2;
expMult = 1.5;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].AevumSnapFitnessGym.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Aevum) {
workerScript.scriptRef.log("ERROR: You cannot workout at Snap Fitness because you are not in Aevum. gymWorkout() failed");
return false;
}
costMult = 6;
expMult = 4;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12IronGym.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot workout at Iron Gym because you are not in Sector-12. gymWorkout() failed");
return false;
}
costMult = 1;
expMult = 1;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12PowerhouseGym.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12) {
workerScript.scriptRef.log("ERROR: You cannot workout at Powerhouse Gym because you are not in Sector-12. gymWorkout() failed");
return false;
}
costMult = 10;
expMult = 7.5;
break;
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].VolhavenMilleniumFitnessGym:
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city != __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Volhaven) {
workerScript.scriptRef.log("ERROR: You cannot workout at Millenium Fitness Gym because you are not in Volhaven. gymWorkout() failed");
return false;
}
costMult = 3;
expMult = 2.5;
break;
default:
workerScript.scriptRef.log("Invalid gym name: " + gymName + ". gymWorkout() failed");
return false;
}
switch(stat.toLowerCase()) {
case "strength".toLowerCase():
case "str".toLowerCase():
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassGymStrength);
break;
case "defense".toLowerCase():
case "def".toLowerCase():
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassGymDefense);
break;
case "dexterity".toLowerCase():
case "dex".toLowerCase():
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassGymDexterity);
break;
case "agility".toLowerCase():
case "agi".toLowerCase():
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startClass(costMult, expMult, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].ClassGymAgility);
break;
default:
workerScript.scriptRef.log("Invalid stat: " + stat + ". gymWorkout() failed");
return false;
}
workerScript.scriptRef.log("Started training " + stat + " at " + gymName);
return true;
},
travelToCity(cityname) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run travelToCity(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
switch(cityname) {
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Aevum:
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Chongqing:
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Sector12:
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].NewTokyo:
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Ishima:
case __WEBPACK_IMPORTED_MODULE_8__Location_js__["a" /* Locations */].Volhaven:
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(200000);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].city = cityname;
workerScript.scriptRef.log("Traveled to " + cityname);
return true;
default:
workerScript.scriptRef.log("ERROR: Invalid city name passed into travelToCity().");
return false;
}
},
purchaseTor() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseTor(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] != null) {
workerScript.scriptRef.log("You already have a TOR router! purchaseTor() failed");
return false;
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.lt(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].TorRouterCost)) {
workerScript.scriptRef.log("ERROR: You cannot afford to purchase a Tor router. purchaseTor() failed");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].TorRouterCost);
var darkweb = new __WEBPACK_IMPORTED_MODULE_11__Server_js__["d" /* Server */](Object(__WEBPACK_IMPORTED_MODULE_21__utils_IPAddress_js__["a" /* createRandomIp */])(), "darkweb", "", false, false, false, 1);
Object(__WEBPACK_IMPORTED_MODULE_11__Server_js__["a" /* AddToAllServers */])(darkweb);
__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */].addIp("Darkweb Server", darkweb.ip);
document.getElementById("location-purchase-tor").setAttribute("class", "a-link-button-inactive");
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().serversOnNetwork.push(darkweb.ip);
darkweb.serversOnNetwork.push(__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().ip);
workerScript.scriptRef.log("You have purchased a Tor router!");
return true;
},
purchaseProgram(programName) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 1)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseProgram(). It is a Singularity Function and requires SourceFile-4 (level 1) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_13__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"] == null) {
workerScript.scriptRef.log("ERROR: You do not have TOR router. purchaseProgram() failed.");
return false;
}
switch(programName.toLowerCase()) {
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].BruteSSHProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].BruteSSHProgram);
workerScript.scriptRef.log("You have purchased the BruteSSH.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + programName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].FTPCrackProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].FTPCrackProgram);
workerScript.scriptRef.log("You have purchased the FTPCrack.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].RelaySMTPProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram);
workerScript.scriptRef.log("You have purchased the relaySMTP.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].HTTPWormProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].HTTPWormProgram);
workerScript.scriptRef.log("You have purchased the HTTPWorm.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].SQLInjectProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].SQLInjectProgram);
workerScript.scriptRef.log("You have purchased the SQLInject.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV1Program);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV1);
workerScript.scriptRef.log("You have purchased the DeepscanV1.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase():
var price = Object(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["d" /* parseDarkwebItemPrice */])(__WEBPACK_IMPORTED_MODULE_4__DarkWeb_js__["a" /* DarkWebItems */].DeepScanV2Program);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV2);
workerScript.scriptRef.log("You have purchased the DeepscanV2.exe program. The new program " +
"can be found on your home computer.");
} else {
workerScript.scriptRef.log("Not enough money to purchase " + itemName);
}
return true;
default:
workerScript.scriptRef.log("ERROR: Invalid program passed into purchaseProgram().");
return false;
}
return true;
},
upgradeHomeRam() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run upgradeHomeRam(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
//Calculate how many times ram has been upgraded (doubled)
var currentRam = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().maxRam;
var numUpgrades = Math.log2(currentRam);
//Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded
var cost = currentRam * __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome;
var mult = Math.pow(1.55, numUpgrades);
cost = cost * mult;
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].money.lt(cost)) {
workerScript.scriptRef.log("ERROR: upgradeHomeRam() failed because you don't have enough money");
return false;
}
var homeComputer = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer();
homeComputer.maxRam *= 2;
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].loseMoney(cost);
workerScript.scriptRef.log("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
return true;
},
getUpgradeHomeRamCost() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getUpgradeHomeRamCost(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
//Calculate how many times ram has been upgraded (doubled)
var currentRam = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].getHomeComputer().maxRam;
var numUpgrades = Math.log2(currentRam);
//Calculate cost
//Have cost increase by some percentage each time RAM has been upgraded
var cost = currentRam * __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].BaseCostFor1GBOfRamHome;
var mult = Math.pow(1.55, numUpgrades);
return cost * mult;
},
workForCompany() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyPosition == "" || !(__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyPosition instanceof __WEBPACK_IMPORTED_MODULE_1__Company_js__["c" /* CompanyPosition */])) {
workerScript.scriptRef.log("ERROR: workForCompany() failed because you do not have a job");
return false;
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].isWorking) {
var txt = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].singularityStopWork();
workerScript.scriptRef.log(txt);
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyPosition.isPartTimeJob()) {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startWorkPartTime();
} else {
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startWork();
}
workerScript.scriptRef.log("Began working at " + __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyName + " as a " + __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyPosition.positionName);
return true;
},
applyToCompany(companyName, field) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run applyToCompany(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (!Object(__WEBPACK_IMPORTED_MODULE_1__Company_js__["e" /* companyExists */])(companyName)) {
workerScript.scriptRef.log("ERROR: applyToCompany() failed because specified company " + companyName + " does not exist.");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].location = companyName;
var res;
switch (field.toLowerCase()) {
case "software":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForSoftwareJob(true);
break;
case "software consultant":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForSoftwareConsultantJob(true);
break;
case "it":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForItJob(true);
break;
case "security engineer":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForSecurityEngineerJob(true);
break;
case "network engineer":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForNetworkEngineerJob(true);
break;
case "business":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForBusinessJob(true);
break;
case "business consultant":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForBusinessConsultantJob(true);
break;
case "security":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForSecurityJob(true);
break;
case "agent":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForAgentJob(true);
break;
case "employee":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForEmployeeJob(true);
break;
case "part-time employee":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForPartTimeEmployeeJob(true);
break;
case "waiter":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].applyForWaiterJob(true);
break;
case "part-time waiter":
res = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["e" /* isString */])(res)) {
workerScript.scriptRef.log(res);
return false;
}
if (res) {
workerScript.scriptRef.log("You were offered a new job at " + companyName + " as a " + __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].companyPosition.positionName);
} else {
workerScript.scriptRef.log("You failed to get a new job/promotion at " + companyName + " in the " + field + " field.");
}
return res;
},
getCompanyRep(companyName) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getCompanyRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
var company = __WEBPACK_IMPORTED_MODULE_1__Company_js__["a" /* Companies */][companyName];
if (company === null || !(company instanceof __WEBPACK_IMPORTED_MODULE_1__Company_js__["b" /* Company */])) {
workerScript.scriptRef.log("ERROR: Invalid companyName passed into getCompanyRep(): " + companyName);
return -1;
}
return company.playerReputation;
},
checkFactionInvitations() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* 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 __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].factionInvitations.slice();
},
joinFaction(name) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run joinFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (!Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["d" /* factionExists */])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in joinFaction() does not exist.");
return false;
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].factionInvitations.includes(name)) {
workerScript.scriptRef.log("ERROR: Cannot join " + name + " Faction because you have not been invited. joinFaction() failed");
return false;
}
var index = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].factionInvitations.splice(index, 1);
var fac = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][name];
Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["h" /* joinFaction */])(fac);
workerScript.scriptRef.log("Joined the " + name + " faction.");
return true;
},
workForFaction(name, type) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run workForFaction(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return false;
}
}
if (!Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["d" /* factionExists */])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in workForFaction() does not exist.");
return false;
}
if (!__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].factions.includes(name)) {
workerScript.scriptRef.log("ERROR: workForFaction() failed because you are not a member of " + name);
return false;
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].isWorking) {
var txt = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].singularityStopWork();
workerScript.scriptRef.log(txt);
}
var fac = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* 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;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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(name) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 2)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getFactionRep(). It is a Singularity Function and requires SourceFile-4 (level 2) to run.");
return -1;
}
}
if (!Object(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["d" /* factionExists */])(name)) {
workerScript.scriptRef.log("ERROR: Faction specified in getFactionRep() does not exist.");
return -1;
}
return __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][name].playerReputation;
},
createProgram(name) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run createProgram(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].isWorking) {
var txt = __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].singularityStopWork();
workerScript.scriptRef.log(txt);
}
switch(name.toLowerCase()) {
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].NukeProgram.toLowerCase():
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].NukeProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes, 1);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 50) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create BruteSSH (level 50 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].BruteSSHProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerFiveMinutes * 2, 50);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 100) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create FTPCrack (level 100 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].FTPCrackProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 100);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 250) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create relaySMTP (level 250 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 250);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 500) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create HTTPWorm (level 500 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].HTTPWormProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPer4Hours, 500);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 750) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create SQLInject (level 750 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].SQLInjectProgram, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPer8Hours, 750);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 75) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV1 (level 75 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV1, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 75);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 400) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create DeepscanV2 (level 400 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].DeepscanV2, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPer2Hours, 400);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].ServerProfiler.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 75) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create ServerProfiler (level 75 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].ServerProfiler, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerHalfHour, 75);
break;
case __WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].AutoLink.toLowerCase():
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].hacking_skill < 25) {
workerScript.scriptRef.log("ERROR: createProgram() failed because hacking level is too low to create AutoLink (level 25 req)");
return false;
}
__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].startCreateProgramWork(__WEBPACK_IMPORTED_MODULE_3__CreateProgram_js__["a" /* Programs */].AutoLink, __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].MillisecondsPerQuarterHour, 25);
break;
default:
workerScript.scriptRef.log("ERROR: createProgram() failed because the specified program does not exist: " + name);
return false;
}
workerScript.scriptRef.log("Began creating program: " + name);
return true;
},
getAugmentationCost(name) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run getAugmentationCost(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (!Object(__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["f" /* augmentationExists */])(name)) {
workerScript.scriptRef.log("ERROR: getAugmentationCost() failed. Invalid Augmentation name passed in (note: this is case-sensitive): " + name);
return [-1, -1];
}
var aug = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][name];
return [aug.baseRepRequirement, aug.baseCost];
},
purchaseAugmentation(faction, name) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run purchaseAugmentation(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
var fac = __WEBPACK_IMPORTED_MODULE_6__Faction_js__["b" /* Factions */][faction];
if (fac === null || !(fac instanceof __WEBPACK_IMPORTED_MODULE_6__Faction_js__["a" /* 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 = __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["c" /* Augmentations */][name];
if (aug === null || !(aug instanceof __WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["a" /* Augmentation */])) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because of invalid augmentation name: " + name);
return false;
}
for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].queuedAugmentations.length; ++j) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].queuedAugmentations[j].name === aug.name) {
workerScript.scriptRef.log("ERROR: purchaseAugmentation() failed because you already have " + name);
return false;
}
}
for (var j = 0; j < __WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].augmentations.length; ++j) {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__Faction_js__["k" /* purchaseAugmentation */])(aug, fac, true);
workerScript.scriptRef.log(res);
if (Object(__WEBPACK_IMPORTED_MODULE_22__utils_StringHelperFunctions_js__["e" /* isString */])(res) && res.startsWith("You purchased")) {
return true;
} else {
return false;
}
},
installAugmentations() {
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].bitNodeN != 4) {
if (!(hasSingularitySF && singularitySFLvl >= 3)) {
throw Object(__WEBPACK_IMPORTED_MODULE_17__NetscriptEvaluator_js__["c" /* makeRuntimeRejectMsg */])(workerScript, "Cannot run installAugmentations(). It is a Singularity Function and requires SourceFile-4 (level 3) to run.");
return false;
}
}
if (__WEBPACK_IMPORTED_MODULE_9__Player_js__["a" /* Player */].queuedAugmentations.length === 0) {
workerScript.scriptRef.log("ERROR: installAugmentations() failed because you do not have any Augmentations to be installed");
return false;
}
workerScript.scriptRef.log("Installing Augmentations. This will cause this script to be killed");
Object(__WEBPACK_IMPORTED_MODULE_0__Augmentations_js__["h" /* installAugmentations */])();
return true;
}
}
}
/***/ }),
/* 40 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return commitShopliftCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return commitRobStoreCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return commitMugCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return commitLarcenyCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return commitDealDrugsCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return commitTraffickArmsCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return commitHomicideCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return commitGrandTheftAutoCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return commitKidnapCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return commitAssassinationCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return commitHeistCrime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return determineCrimeSuccess; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return determineCrimeChanceShoplift; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return determineCrimeChanceRobStore; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return determineCrimeChanceMug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return determineCrimeChanceLarceny; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return determineCrimeChanceDealDrugs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return determineCrimeChanceTraffickArms; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return determineCrimeChanceHomicide; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return determineCrimeChanceGrandTheftAuto; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return determineCrimeChanceKidnap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return determineCrimeChanceAssassination; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return determineCrimeChanceHeist; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__utils_DialogBox_js__ = __webpack_require__(2);
/* Crimes.js */
function commitShopliftCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeShoplift;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 0, 0, 2, 2, 0, 15000, 2000); //$7500/s, 1 exp/s
}
function commitRobStoreCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeRobStore;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(30, 0, 0, 45, 45, 0, 400000, 60000); //$6666,6/2, 0.5exp/s, 0.75exp/s
}
function commitMugCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeMug;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 3, 3, 3, 3, 0, 36000, 4000); //$9000/s, .66 exp/s
}
function commitLarcenyCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeLarceny;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(45, 0, 0, 60, 60, 0, 800000, 90000) // $8888.88/s, .5 exp/s, .66 exp/s
}
function commitDealDrugsCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeDrugs;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 0, 0, 5, 5, 10, 120000, 10000); //$12000/s, .5 exp/s, 1 exp/s
}
function commitTraffickArmsCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeTraffickArms;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 20, 20, 20, 20, 40, 600000, 40000); //$15000/s, .5 combat exp/s, 1 cha exp/s
}
function commitHomicideCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeHomicide;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 2, 2, 2, 2, 0, 45000, 3000); //$15000/s, 0.66 combat exp/s
}
function commitGrandTheftAutoCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeGrandTheftAuto;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 20, 20, 20, 80, 40, 1600000, 80000); //$20000/s, .25 exp/s, 1 exp/s, .5 exp/s
}
function commitKidnapCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeKidnap;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 80, 80, 80, 80, 80, 3600000, 120000); //$30000/s. .66 exp/s
}
function commitAssassinationCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeAssassination;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(0, 300, 300, 300, 300, 0, 12000000, 300000); //$40000/s, 1 exp/s
}
function commitHeistCrime() {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crimeType = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeHeist;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].startCrime(450, 450, 450, 450, 450, 450, 120000000, 600000); //$200000/s, .75exp/s
}
function determineCrimeSuccess(crime, moneyGained) {
var chance = 0;
switch (crime) {
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeShoplift:
chance = determineCrimeChanceShoplift();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeRobStore:
chance = determineCrimeChanceRobStore();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeMug:
chance = determineCrimeChanceMug();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeLarceny:
chance = determineCrimeChanceLarceny();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeDrugs:
chance = determineCrimeChanceDealDrugs();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeTraffickArms:
chance = determineCrimeChanceTraffickArms();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeHomicide:
chance = determineCrimeChanceHomicide();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeGrandTheftAuto:
chance = determineCrimeChanceGrandTheftAuto();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeKidnap:
chance = determineCrimeChanceKidnap();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeAssassination:
chance = determineCrimeChanceAssassination();
break;
case __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].CrimeHeist:
chance = determineCrimeChanceHeist();
break;
default:
console.log(crime);
Object(__WEBPACK_IMPORTED_MODULE_2__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERR: Unrecognized crime type. This is probably a bug please contact the developer");
return;
}
if (Math.random() <= chance) {
//Success
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].gainMoney(moneyGained);
return true;
} else {
//Failure
return false;
}
}
function determineCrimeChanceShoplift() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) * 20;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceRobStore() {
var chance = ((0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
1 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) * 5;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceMug() {
var chance = ((1.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].defense / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
1.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) * 5;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceLarceny() {
var chance = ((0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) * 3;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceDealDrugs() {
var chance = ((3*__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].charisma / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2*__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel));
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceTraffickArms() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].charisma / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].defense / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) / 2;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceHomicide() {
var chance = ((2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].defense / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
0.5 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel));
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceGrandTheftAuto() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
4 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].charisma / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) / 8;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceKidnap() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].charisma / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) / 5;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceAssassination() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
2 * __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) / 8;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
function determineCrimeChanceHeist() {
var chance = ((__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].hacking_skill / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].strength / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].defense / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].dexterity / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].agility / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel +
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].charisma / __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].MaxSkillLevel)) / 18;
chance *= __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].crime_success_mult;
return Math.min(chance, 1);
}
/***/ }),
/* 41 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Aliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return GlobalAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return printAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return parseAliasDeclaration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return removeAlias; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return substituteAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return loadAliases; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return loadGlobalAliases; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Terminal_js__ = __webpack_require__(19);
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(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* post */])("alias " + name + "=" + Aliases[name]);
}
}
for (var name in GlobalAliases) {
if (GlobalAliases.hasOwnProperty(name)) {
Object(__WEBPACK_IMPORTED_MODULE_0__Terminal_js__["b" /* 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(" ");
}
/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkIfConnectedToDarkweb; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return executeDarkwebTerminalCommand; });
/* unused harmony export listAllDarkwebItems */
/* unused harmony export buyDarkwebItem */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return parseDarkwebItemPrice; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DarkWebItems; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Terminal_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* DarkWeb.js */
//Posts a "help" message if connected to DarkWeb
function checkIfConnectedToDarkweb() {
if (__WEBPACK_IMPORTED_MODULE_2__SpecialServerIps_js__["a" /* SpecialServerIps */].hasOwnProperty("Darkweb Server")) {
var darkwebIp = __WEBPACK_IMPORTED_MODULE_2__SpecialServerIps_js__["a" /* SpecialServerIps */]["Darkweb Server"];
if (!isValidIPAddress(darkwebIp)) {return;}
if (darkwebIp == __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getCurrentServer().ip) {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You are now connected to the dark web. From the dark web you can purchase illegal items. " +
"Use the 'buy -l' command to display a list of all the items you can buy. Use 'buy [item-name] " +
"to purchase an item");
}
}
}
//Handler for dark web commands. The terminal's executeCommand() function will pass
//dark web-specific commands into this. It will pass in the raw split command array
//rather than the command string
function executeDarkwebTerminalCommand(commandArray) {
if (commandArray.length == 0) {return;}
switch (commandArray[0]) {
case "buy":
if (commandArray.length != 2) {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Incorrect number of arguments. Usage: ");
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("buy -l");
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("buy [item name]");
return;
}
var arg = commandArray[1];
if (arg == "-l") {
listAllDarkwebItems();
} else {
buyDarkwebItem(arg);
}
break;
default:
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Command not found");
break;
}
}
function listAllDarkwebItems() {
for (var item in DarkWebItems) {
if (DarkWebItems.hasOwnProperty(item)) {
var item = DarkWebItems[item];
//Convert string using toLocaleString
var split = item.split(" - ");
if (split.length == 3 && split[1].charAt(0) == '$') {
split[1] = split[1].slice(1);
split[1] = split[1].replace(/,/g, '');
var price = parseFloat(split[1]);
if (isNaN(price)) {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])(item);
return;
}
price = Object(__WEBPACK_IMPORTED_MODULE_4__utils_StringHelperFunctions_js__["c" /* formatNumber */])(price, 0);
split[1] = "$" + price.toString();
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])(split.join(" - "));
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])(item);
}
}
}
var priceString = split[1];
//Check for errors
if (priceString.length == 0 || priceString.charAt(0) != '$') {
return -1;
}
//Remove dollar sign and commas
priceString = priceString.slice(1);
priceString = priceString.replace(/,/g, '');
//Convert string to numeric
var price = parseFloat(priceString);
if (isNaN(price)) {return -1;}
else {return price;}
}
function buyDarkwebItem(itemName) {
if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].BruteSSHProgram.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.BruteSSHProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].BruteSSHProgram);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the BruteSSH.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].FTPCrackProgram.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.FTPCrackProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].FTPCrackProgram);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the FTPCrack.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.RelaySMTPProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].RelaySMTPProgram);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the relaySMTP.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].HTTPWormProgram.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.HTTPWormProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].HTTPWormProgram);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the HTTPWorm.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].SQLInjectProgram.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.SQLInjectProgram);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].SQLInjectProgram);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the SQLInject.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].DeepscanV1.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV1Program);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].DeepscanV1);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the DeepscanV1.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else if (itemName.toLowerCase() == __WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].DeepscanV2.toLowerCase()) {
var price = parseDarkwebItemPrice(DarkWebItems.DeepScanV2Program);
if (price > 0 && __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.gt(price)) {
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(price);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer().programs.push(__WEBPACK_IMPORTED_MODULE_0__CreateProgram_js__["a" /* Programs */].DeepscanV2);
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("You have purchased the DeepscanV2.exe program. The new program " +
"can be found on your home computer.");
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Not enough money to purchase " + itemName);
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_3__Terminal_js__["b" /* post */])("Unrecognized item");
}
}
function parseDarkwebItemPrice(itemDesc) {
var split = itemDesc.split(" - ");
if (split.length == 3) {
var priceString = split[1];
//Check for errors
if (priceString.length == 0 || priceString.charAt(0) != '$') {
return -1;
}
//Remove dollar sign and commas
priceString = priceString.slice(1);
priceString = priceString.replace(/,/g, '');
//Convert string to numeric
var price = parseFloat(priceString);
if (isNaN(price)) {return -1;}
else {return price;}
} else {
return -1;
}
}
let DarkWebItems = {
BruteSSHProgram: "BruteSSH.exe - $500,000 - Opens up SSH Ports",
FTPCrackProgram: "FTPCrack.exe - $1,500,000 - Opens up FTP Ports",
RelaySMTPProgram: "relaySMTP.exe - $5,000,000 - Opens up SMTP Ports",
HTTPWormProgram: "HTTPWorm.exe - $30,000,000 - Opens up HTTP Ports",
SQLInjectProgram: "SQLInject.exe - $250,000,000 - Opens up SQL Ports",
DeepScanV1Program: "DeepscanV1.exe - $500,000 - Enables 'scan-analyze' with a depth up to 5",
DeepScanV2Program: "DeepscanV2.exe - $25,000,000 - Enables 'scan-analyze' with a depth up to 10",
}
/***/ }),
/* 43 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export Literatures */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return initLiterature; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return showLiterature; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__ = __webpack_require__(2);
/* Literature.js
* Lore / world building literature that can be found on servers
*/
function Literature(title, filename, txt) {
this.title = title;
this.fn = filename;
this.txt = txt;
}
function showLiterature(fn) {
var litObj = Literatures[fn];
if (litObj == null) {return;}
var txt = litObj.title + "<br><br>" +
"<i>" + litObj.txt + "</i>";
Object(__WEBPACK_IMPORTED_MODULE_0__utils_DialogBox_js__["a" /* dialogBoxCreate */])(txt);
}
let Literatures = {}
function initLiterature() {
var title, fn, txt;
title = "A Green Tomorrow";
fn = "A-Green-Tomorrow.lit";
txt = "Starting a few decades ago, there was a massive global movement towards the generation of renewable energy in an effort to " +
"combat global warming and climate change. The shift towards renewable energy was a big success, or so it seemed. In 2045 " +
"a staggering 80% of the world's energy came from non-renewable fossil fuels. Now, about three decades later, that " +
"number is down to only 15%. Most of the world's energy now comes from nuclear power and renwable sources such as " +
"solar and geothermal. Unfortunately, these efforts were not the huge success that they seem to be.<br><br>" +
"Since 2045 primary energy use has soared almost tenfold. This was mainly due to growing urban populations and " +
"the rise of increasingly advanced (and power-hungry) technology that has become ubiquitous in our lives. So, " +
"despite the fact that the percentage of our energy that comes from fossil fuels has drastically decreased, " +
"the total amount of energy we are producing from fossil fuels has actually increased.<br><br>" +
"The grim effects of our species' irresponsible use of energy and neglect of our mother world have become increasingly apparent. " +
"Last year a temperature of 190F was recorded in the Death Valley desert, which is over 50% higher than the highest " +
"recorded temperature at the beginning of the century. In the last two decades numerous major cities such as Manhattan, Boston, and " +
"Los Angeles have been partially or fully submerged by rising sea levels. In the present day, over 75% of the world's agriculture is " +
"done in climate-controlled vertical farms, as most traditional farmland has become unusable due to severe climate conditions.<br><br>" +
"Despite all of this, the greedy and corrupt corporations that rule the world have done nothing to address these problems that " +
"threaten our species. And so it's up to us, the common people. Each and every one of us can make a difference by doing what " +
"these corporations won't: taking responsibility. If we don't, pretty soon there won't be an Earth left to save. We are " +
"the last hope for a green tomorrow.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Alpha and Omega";
fn = "alpha-omega.lit";
txt = "Then we saw a new heaven and a new earth, for our first heaven and earth had gone away, and our sea was no more. " +
"And we saw a new holy city, new Aeria, coming down out of this new heaven, prepared as a bride adorned for her husband. " +
"And we heard a loud voice saying, 'Behold, the new dwelling place of the Gods. We will dwell with them, and they " +
"will be our people, and we will be with them as their Gods. We will wipe away every tear from their eyes, and death " +
"shall be no more, neither shall there be mourning, nor crying, nor pain anymore, for the former things " +
"have passed away.'<br><br>" +
"And once were were seated on the throne we said 'Behold, I am making all things new.' " +
"Also we said, 'Write this down, for these words are trustworthy and true.' And we said to you, " +
"'It is done! I am the Alpha and the Omega, the beginning and the end. To the thirsty I will give from the spring " +
"of the water of life without payment. The one who conquers will have this heritage, and we will be his God and " +
"he will be our son. But as for the cowardly, the faithless, the detestable, as for murderers, " +
"the sexually immoral, sorcerers, idolaters, and all liars, their portion will be in the lake that " +
"burns with fire and sulfur, for it is the second true death.'";
Literatures[fn] = new Literature(title, fn, txt);
title = "Are We Living in a Computer Simulation?";
fn = "simulated-reality.lit";
txt = "The idea that we are living in a virtual world is not new. It's a trope that has " +
"been explored constantly in literature and pop culture. However, it is also a legitimate " +
"scientific hypothesis that many notable physicists and philosophers have debated for years.<br><br>" +
"Proponents for this simulated reality theory often point to how advanced our technology has become, " +
"as well as the incredibly fast pace at which it has advanced over the past decades. The amount of computing " +
"power available to us has increased over 100-fold since 2060 due to the development of nanoprocessors and " +
"quantum computers. Artifical Intelligence has advanced to the point where our entire lives are controlled " +
"by robots and machines that handle our day-to-day activities such as autonomous transportation and scheduling. " +
"If we consider the pace at which this technology has advanced and assume that these developments continue, it's " +
"reasonable to assume that at some point in the future our technology would be advanced enough that " +
"we could create simulations that are indistinguishable from reality. However, if this is a reasonable outcome " +
"of continued technological advancement, then it is very likely that such a scenario has already happened. <br><br>" +
"Statistically speaking, somewhere out there in the infinite universe there is an advanced, intelligent species " +
"that already has such technology. Who's to say that they haven't already created such a virtual reality: our own?";
Literatures[fn] = new Literature(title, fn, txt);
title = "Beyond Man";
fn = "beyond-man.lit";
txt = "Humanity entered a 'transhuman' era a long time ago. And despite the protests and criticisms of many who cried out against " +
"human augmentation at the time, the transhuman movement continued and prospered. Proponents of the movement ignored the critics, " +
"arguing that it was in our inherent nature to better ourselves. To improve. To be more than we were. They claimed that " +
"not doing so would be to go against every living organism's biological purpose: evolution and survival of the fittest.<br><br>" +
"And here we are today, with technology that is advanced enough to augment humans to a state that " +
"can only be described as posthuman. But what do we have to show for it when this augmentation " +
"technology is only available to the so-called 'elite'? Are we really better off than before when only 5% of the " +
"world's population has access to this technology? When the powerful corporations and organizations of the world " +
"keep it all to themselves, have we really evolved?<br><br>" +
"Augmentation technology has only further increased the divide between the rich and the poor, between the powerful and " +
"the oppressed. We have not become 'more than human'. We have not evolved from nature's original design. We are still the greedy, " +
"corrupted, and evil men that we always were.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Brighter than the Sun";
fn = "brighter-than-the-sun.lit";
txt = "When people think about the corporations that dominate the East, they typically think of KuaiGong International, which " +
"holds a complete monopoly for manufacturing and commerce in Asia, or Global Pharmaceuticals, the world's largest " +
"drug company, or OmniTek Incorporated, the global leader in intelligent and autonomous robots. But there's one company " +
"that has seen a rapid rise in the last year and is poised to dominate not only the East, but the entire world: TaiYang Digital.<br><br>" +
"TaiYang Digital is a Chinese internet-technology corporation that provides services such as " +
"online advertising, search, gaming, media, entertainment, and cloud computing/storage. Its name TaiYang comes from the Chinese word " +
"for 'sun'. In Chinese culture, the sun is a 'yang' symbol " +
"associated with life, heat, masculinity, and heaven.<br><br>" +
"The company was founded " +
"less than 5 years ago and is already the third highest valued company in all of Asia. In 2076 it generated a total revenue of " +
"over 10 trillion yuan. It's services are used daily by over a billion people worldwide.<br><br>" +
"TaiYang Digital's meteoric rise is extremely surprising in modern society. This sort of growth is " +
"something you'd commonly see in the first half of the century, especially for tech companies. However in " +
"the last two decades the number of corporations has significantly declined as the largest entities " +
"quickly took over the economy. Corporations such as ECorp, MegaCorp, and KuaiGong have established " +
"such strong monopolies in their market sectors that they have effectively killed off all " +
"of the smaller and new corporations that have tried to start up over the years. This is what makes " +
"the rise of TaiYang Digital so impressive. And if TaiYang continues down this path, then they have " +
"a bright future ahead of them.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Democracy is Dead: The Fall of an Empire";
fn = "democracy-is-dead.lit";
txt = "They rose from the shadows in the street<br>From the places where the oppressed meet<br>" +
"Their cries echoed loudly through the air<br>As they once did in Tiananmen Square<br>" +
"Loudness in the silence, Darkness in the light<br>They came forth with power and might<br>" +
"Once the beacon of democracy, America was first<br>Its pillars of society destroyed and dispersed<br>" +
"Soon the cries rose everywhere, with revolt and riot<br>Until one day, finally, all was quiet<br>" +
"From the ashes rose a new order, corporatocracy was its name<br>" +
"Rome, Mongol, Byzantine, all of history is just the same<br>" +
"For man will never change in a fundamental way<br>" +
"And now democracy is dead, in the USA";
Literatures[fn] = new Literature(title, fn, txt);
title = "Figures Show Rising Crime Rates in Sector-12";
fn = "sector-12-crime.lit";
txt = "A recent study by analytics company Wilson Inc. shows a significant rise " +
"in criminal activity in Sector-12. Perhaps the most alarming part of the statistic " +
"is that most of the rise is in violent crime such as homicide and assault. According " +
"to the study, the city saw a total of 21,406 reported homicides in 2076, which is over " +
"a 20% increase compared to 2075.<br><br>" +
"CIA director David Glarow says its too early to know " +
"whether these figures indicate the beginning of a sustained increase in crime rates, or whether " +
"the year was just an unfortunate outlier. He states that many intelligence and law enforcement " +
"agents have noticed an increase in organized crime activites, and believes that these figures may " +
"be the result of an uprising from criminal organizations such as The Syndicate or the Slum Snakes.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Man and the Machine";
fn = "man-and-machine.lit";
txt = "In 2005 Ray Kurzweil popularized his theory of the Singularity. He predicted that the rate " +
"of technological advancement would continue to accelerate faster and faster until one day " +
"machines would be become infinitely more intelligent than humans. This point, called the " +
"Singularity, would result in a drastic transformation of the world as we know it. He predicted " +
"that the Singularity would arrive by 2045. " +
"And yet here we are, more than three decades later, where most would agree that we have not " +
"yet reached a point where computers and machines are vastly more intelligent than we are. So what gives?<br><br>" +
"The answer is that we have reached the Singularity, just not in the way we expected. The artifical superintelligence " +
"that was predicted by Kurzweil and others exists in the world today - in the form of Augmentations. " +
"Yes, those Augmentations that the rich and powerful keep to themselves enable humans " +
"to become superintelligent beings. The Singularity did not lead to a world where " +
"our machines are infinitely more intelligent than us, it led to a world " +
"where man and machine can merge to become something greater. Most of the world just doesn't " +
"know it yet."
Literatures[fn] = new Literature(title, fn, txt);
title = "Secret Societies";
fn = "secret-societies.lit";
txt = "The idea of secret societies has long intrigued the general public by inspiring curiosity, fascination, and " +
"distrust. People have long wondered about who these secret society members are and what they do, with the " +
"most radical of conspiracy theorists claiming that they control everything in the entire world. And while the world " +
"may never know for sure, it is likely that many secret societies do actually exist, even today.<br><br>" +
"However, the secret societies of the modern world are nothing like those that (supposedly) existed " +
"decades and centuries ago. The Freemasons, Knights Templar, and Illuminati, while they may have been around " +
"at the turn of the 21st century, almost assuredly do not exist today. The dominance of the Web in " +
"our everyday lives and the fact that so much of the world is now digital has given rise to a new breed " +
"of secret societies: Internet-based ones.<br><br>" +
"Commonly called 'hacker groups', Internet-based secret societies have become well-known in today's " +
"world. Some of these, such as The Black Hand, are black hat groups that claim they are trying to " +
"help the oppressed by attacking the elite and powerful. Others, such as NiteSec, are hacktivist groups " +
"that try to push political and social agendas. Perhaps the most intriguing hacker group " +
"is the mysterious Bitrunners, whose purpose still remains unknown.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Space: The Failed Frontier";
fn = "the-failed-frontier.lit";
txt = "Humans have long dreamed about spaceflight. With enduring interest, we were driven to explore " +
"the unknown and discover new worlds. We dreamed about conquering the stars. And in our quest, " +
"we pushed the boundaries of our scientific limits, and then pushed further. Space exploration " +
"lead to the development of many important technologies and new industries.<br><br>" +
"But sometime in the middle of the 21st century, all of that changed. Humanity lost its ambitions and " +
"aspirations of exploring the cosmos. The once-large funding for agencies like NASA and the European " +
"Space Agency gradually whittled away until their eventual disbanding in the 2060's. Not even " +
"militaries are fielding flights into space nowadays. The only remnants of the once great mission for cosmic " +
"conquest are the countless satellites in near-earth orbit, used for communications, espionage, " +
"and other corporate interests.<br><br>" +
"And as we continue to look at the state of space technology, it becomes more and " +
"more apparent that we will never return to that golden age of space exploration, that " +
"age where everyone dreamed of going beyond earth for the sake of discovery.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Coded Intelligence: Myth or Reality?";
fn = "coded-intelligence.lit";
txt = "Tremendous progress has been made in the field of Artificial Intelligence over the past few decades. " +
"Our autonomous vehicles and transporation systems. The electronic personal assistants that control our everyday lives. " +
"Medical, service, and manufacturing robots. All of these are examples of how far AI has come and how much it has " +
"improved our daily lives. However, the question still remains of whether AI will ever be advanced enough to re-create " +
"human intelligence.<br><br>" +
"We've certainly come close to artificial intelligence that is similar to humans. For example OmniTek Incorporated's " +
"CompanionBot, a robot meant to act as a comforting friend for lonely and grieving people, is eerily human-like " +
"in its appearance, speech, mannerisms, and even movement. However its artificial intelligence isn't the same as " +
"that of humans. Not yet. It doesn't have sentience or self-awareness or consciousness.<br><br>" +
"Many neuroscientists believe that we won't ever reach the point of creating artificial human intelligence. 'At the end of the " +
"the day, AI comes down to 1's and 0's, while the human brain does not. We'll never see AI that is identical to that of " +
"humans.'";
Literatures[fn] = new Literature(title, fn, txt);
title = "Synthetic Muscles";
fn = "synthetic-muscles.lit";
txt = "Initial versions of synthetic muscles weren't made of anything organic but were actually " +
"crude devices made to mimic human muscle function. Some of the early iterations were actually made of " +
"common materials such as fishing lines and sewing threads due to their high strength for " +
"a cheap cost.<br><br>" +
"As technology progressed, however, advances in biomedical engineering paved the way for a new method of " +
"creating synthetic muscles. Instead of creating something that closely imitated the functionality " +
"of human muscle, scientists discovered a way of forcing the human body itself to augment its own " +
"muscle tissue using both synthetic and organic materials. This is typically done using gene therapy " +
"or chemical injections.";
Literatures[fn] = new Literature(title, fn, txt);
title = "Tensions rise in global tech race";
fn = "tensions-in-tech-race.lit";
txt = "Have we entered a new Cold War? Is WWIII just beyond the horizon?<br><br>" +
"After rumors came out that OmniTek Incorporated had begun developing advanced robotic supersoldiers, " +
"geopolitical tensions quickly flared between the USA, Russia, and several Asian superpowers. " +
"In a rare show of cooperation between corporations, MegaCorp and ECorp have " +
"reportedly launched hundreds of new surveillance and espionage satellites. " +
"Defense contractors such as " +
"DeltaOne and AeroCorp have been working with the CIA and NSA to prepare " +
"for conflict. Meanwhile, the rest of the world sits in earnest " +
"hoping that it never reaches full-scale war. With today's technology " +
"and firepower, a World War would assuredly mean the end of human civilization.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Cost of Immortality";
fn = "cost-of-immortality.lit";
txt = "Evolution and advances in medical and augmentation technology has lead to drastic improvements " +
"in human mortality rates. Recent figures show that the life expectancy for humans " +
"that live in a first-world country is about 130 years of age, almost double of what it was " +
"at the turn of the century. However, this increase in average lifespan has had some " +
"significant effects on society and culture.<br><br>" +
"Due to longer lifespans and a better quality of life, many adults are holding " +
"off on having kids until much later. As a result, the percentage of youth in " +
"first-world countries has been decreasing, while the number " +
"of senior citizens is significantly increasing.<br><br>" +
"Perhaps the most alarming result of all of this is the rapidly shrinking workforce. " +
"Despite the increase in life expectancy, the typical retirement age for " +
"workers in America has remained about the same, meaning a larger and larger " +
"percentage of people in America are retirees. Furthermore, many " +
"young adults are holding off on joining the workforce because they feel that " +
"they have plenty of time left in their lives for employment, and want to " +
"'enjoy life while they're young.' For most industries, this shrinking workforce " +
"is not a major issue as most things are handled by robots anyways. However, " +
"there are still several key industries such as engineering and education " +
"that have not been automated, and these remain in danger to this cultural " +
"phenomenon.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Hidden World";
fn = "the-hidden-world.lit";
txt = "WAKE UP SHEEPLE<br><br>" +
"THE GOVERNMENT DOES NOT EXIST. CORPORATIONS DO NOT RUN SOCIETY<br><br>" +
"THE ILLUMINATI ARE THE SECRET RULERS OF THE WORLD!<br><br>" +
"Yes, the Illuminati of legends. The ancient secret society that controls the entire " +
"world from the shadows with their invisible hand. The group of the rich and wealthy " +
"that have penetrated every major government, financial agency, and corporation in the last " +
"three hundred years.<br><br>" +
"OPEN YOUR EYES<br><br>" +
"It was the Illuminati that brought an end to democracy in the world. They are the driving force " +
"behind everything that happens.<br><br>" +
"THEY ARE ALL AROUND YOU<br><br>" +
"After destabilizing the world's governments, they are now entering the final stage of their master plan. " +
"They will secretly initiate global crises. Terrorism. Pandemics. World War. And out of the chaos " +
"that ensues they will build their New World Order.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The New God";
fn = "the-new-god.lit";
txt = "Everyone has that moment in their life where they wonder about the bigger questions<br><br>" +
"What's the point of all of this? What is my purpose?<br><br>" +
"Some people dare to think even bigger<br><br>" +
"What will be the fate of the human race?<br><br>" +
"We live in an era vastly different from that of even 15 or 20 years ago. We have gone " +
"where no man has gone before. We have stripped ourselves of the tyranny of flesh.<br><br>" +
"The Singularity is here. The merging of man and machine. This is where humanity evolves into " +
"something greater. This is our future<br><br>" +
"Embrace it, and you will obey a new god. The God in the Machine";
Literatures[fn] = new Literature(title, fn, txt);
title = "The New Triads";
fn = "new-triads.lit";
txt = "The Triads were an ancient transnational crime syndicate based in China, Hong Kong, and other Asian " +
"territories. They were often considered one of the first and biggest criminal secret societies. " +
"While most of the branches of the Triads have been destroyed over the past few decades, the " +
"crime faction has spawned and inspired a number of other Asian crime organizations over the past few years. " +
"The most notable of these is the Tetrads.<br><br>" +
"It is widely believed that the Tetrads are a rogue group that splintered off from the Triads sometime in the " +
"mid 21st century. The founders of the Tetrads, all of whom were ex-Triad members, believed that the " +
"Triads were losing their purpose and direction. The Tetrads started off as a small group that mainly engaged " +
"in fraud and extortion. They were largely unknown until just a few years ago when they took over the illegal " +
"drug trade in all of the major Asian cities. They quickly became the most powerful crime syndicate in the " +
"continent.<br><br>" +
"Not much else is known about the Tetrads, or about the efforts the Asian governments and corporations are making " +
"to take down this large new crime organization. Many believe that the Tetrads have infiltrated the governments " +
"and powerful corporations in Asia, which has helped faciliate their recent rapid rise.";
Literatures[fn] = new Literature(title, fn, txt);
title = "The Secret War";
fn = "the-secret-war.lit";
txt = ""
Literatures[fn] = new Literature(title, fn, txt);
}
/***/ }),
/* 44 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return redPillFlag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hackWorldDaemon; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__Prestige_js__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__ = __webpack_require__(30);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Terminal_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__ = __webpack_require__(20);
/* RedPill.js
* Implements what happens when you have Red Pill augmentation and then hack the world daemon */
//Returns promise
function writeRedPillLine(line) {
return new Promise(function(resolve, reject) {
var container = document.getElementById("red-pill-container");
var pElem = document.createElement("p");
container.appendChild(pElem);
var promise = writeRedPillLetter(pElem, line, 0);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
});
}
function writeRedPillLetter(pElem, line, i=0) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (i >= line.length) {
var textToShow = line.substring(0, i);
pElem.innerHTML = "> " + textToShow;
return resolve(true);
}
var textToShow = line.substring(0, i);
pElem.innerHTML = "> " + textToShow + "<span class='typed-cursor'> &#9608; </span>";
var promise = writeRedPillLetter(pElem, line, i+1);
promise.then(function(res) {
resolve(res);
}, function(e) {
reject(e);
});
}, 30);
});
}
let redPillFlag = false;
function hackWorldDaemon(currentNodeNumber) {
redPillFlag = true;
__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadRedPillContent();
return writeRedPillLine("[ERROR] SEMPOOL INVALID").then(function() {
return writeRedPillLine("[ERROR] Segmentation Fault");
}).then(function() {
return writeRedPillLine("[ERROR] SIGKILL RECVD");
}).then(function() {
return writeRedPillLine("Dumping core...");
}).then(function() {
return writeRedPillLine("0000 000016FA 174FEE40 29AC8239 384FEA88");
}).then(function() {
return writeRedPillLine("0010 745F696E 2BBBE394 390E3940 248BEC23");
}).then(function() {
return writeRedPillLine("0020 7124696B 0000FF69 74652E6F FFFF1111");
}).then(function() {
return writeRedPillLine("----------------------------------------");
}).then(function() {
return writeRedPillLine("Failsafe initiated...");
}).then(function() {
return writeRedPillLine("Restarting BitNode-" + currentNodeNumber + "...");
}).then(function() {
return writeRedPillLine("...........");
}).then(function() {
return writeRedPillLine("...........");
}).then(function() {
return writeRedPillLine("[ERROR] FAILED TO AUTOMATICALLY REBOOT BITNODE");
}).then(function() {
return writeRedPillLine("..............................................")
}).then(function() {
return writeRedPillLine("..............................................")
}).then(function() {
return loadBitVerse(currentNodeNumber);
}).catch(function(e){
console.log("ERROR: " + e.toString());
});
}
//The bitNode name passed in will have a hyphen between number (e.g. BitNode-1)
//This needs to be removed
function giveSourceFile(bitNodeNumber) {
var sourceFileKey = "SourceFile"+ bitNodeNumber.toString();
var sourceFile = __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["b" /* SourceFiles */][sourceFileKey];
if (sourceFile == null) {
console.log("ERROR: could not find source file for Bit node: " + bitNodeNumber);
return;
}
//Check if player already has this source file
var alreadyOwned = false;
var ownedSourceFile = null;
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.length; ++i) {
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i].n === bitNodeNumber) {
alreadyOwned = true;
ownedSourceFile = __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles[i];
break;
}
}
if (alreadyOwned && ownedSourceFile) {
if (ownedSourceFile.lvl >= 3) {
Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("The Source-File for the BitNode you just destroyed, " + sourceFile.name + ", " +
"is already at max level!");
} else {
++ownedSourceFile.lvl;
Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])(sourceFile.name + " was upgraded to level " + ownedSourceFile.lvl + " for " +
"destroying its corresponding BitNode!");
}
} else {
var playerSrcFile = new __WEBPACK_IMPORTED_MODULE_4__SourceFile_js__["a" /* PlayerOwnedSourceFile */](bitNodeNumber, 1);
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].sourceFiles.push(playerSrcFile);
Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You received a Source-File for destroying a Bit Node!<br><br>" +
sourceFile.name + "<br><br>" + sourceFile.info);
}
}
function loadBitVerse(destroyedBitNodeNum) {
//Clear the screen
var container = document.getElementById("red-pill-container");
while (container.firstChild) {
container.removeChild(container.firstChild);
}
//Create the Bit Verse
var bitVerseImage = document.createElement("pre");
var bitNodes = [];
for (var i = 1; i <= 12; ++i) {
bitNodes.push(createBitNode(i));
}
bitVerseImage.innerHTML =
" O <br>" +
" | O O | O O | <br>" +
" O | | / __| \\ | | O <br>" +
" O | O | | O / | O | | O | O <br>" +
" | | | | |_/ |/ | \\_ \\_| | | | | <br>" +
" O | | | O | | O__/ | / \\__ | | O | | | O <br>" +
" | | | | | | | / /| O / \\| | | | | | | <br>" +
"O | | | \\| | O / _/ | / O | |/ | | | O<br>" +
"| | | |O / | | O / | O O | | \\ O| | | |<br>" +
"| | |/ \\/ / __| | |/ \\ | \\ | |__ \\ \\/ \\| | |<br>" +
" \\| O | |_/ |\\| \\ O \\__| \\_| | O |/ <br>" +
" | | |_/ | | \\| / | \\_| | | <br>" +
" \\| / \\| | / / \\ |/ <br>" +
" | "+bitNodes[9]+" | | / | "+bitNodes[10]+" | <br>" +
" "+bitNodes[8]+" | | | | | | | "+bitNodes[11]+" <br>" +
" | | | / / \\ \\ | | | <br>" +
" \\| | / "+bitNodes[6]+" / \\ "+bitNodes[7]+" \\ | |/ <br>" +
" \\ | / / | | \\ \\ | / <br>" +
" \\ \\JUMP "+bitNodes[4]+"3R | | | | | | R3"+bitNodes[5]+" PMUJ/ / <br>" +
" \\|| | | | | | | | | ||/ <br>" +
" \\| \\_ | | | | | | _/ |/ <br>" +
" \\ \\| / \\ / \\ |/ / <br>" +
" "+bitNodes[0]+" |/ "+bitNodes[1]+" | | "+bitNodes[2]+" \\| "+bitNodes[3]+" <br>" +
" | | | | | | | | <br>" +
" \\JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/ <br><br><br><br>";
/*
" O <br>" +
" | O O | O O | <br>" +
" O | | / __| \ | | O <br>" +
" O | O | | O / | O | | O | O <br>" +
" | | | | |_/ |/ | \_ \_| | | | | <br>" +
" O | | | O | | O__/ | / \__ | | O | | | O <br>" +
" | | | | | | | / /| O / \| | | | | | | <br>" +
"O | | | \| | O / _/ | / O | |/ | | | O<br>" +
"| | | |O / | | O / | O O | | \ O| | | |<br>" +
"| | |/ \/ / __| | |/ \ | \ | |__ \ \/ \| | |<br>" +
" \| O | |_/ |\| \ O \__| \_| | O |/ <br>" +
" | | |_/ | | \| / | \_| | | <br>" +
" \| / \| | / / \ |/ <br>" +
" | O | | / | O | <br>" +
" O | | | | | | | O <br>" +
" | | | / / \ \ | | | <br>" +
" \| | / O / \ O \ | |/ <br>" +
" \ | / / | | \ \ | / <br>" +
" \ \JUMP O3R | | | | | | R3O PMUJ/ / <br>" +
" \|| | | | | | | | | ||/ <br>" +
" \| \_ | | | | | | _/ |/ <br>" +
" \ \| / \ / \ |/ / <br>" +
" O |/ O | | O \| O <br>" +
" | | | | | | | | <br>" +
" \JUMP3R|JUMP|3R| |R3|PMUJ|R3PMUJ/ <br>";
*/
container.appendChild(bitVerseImage);
//Bit node event listeners
for (var i = 1; i <= 12; ++i) {
(function(i) {
var elemId = "bitnode-" + i.toString();
var elem = Object(__WEBPACK_IMPORTED_MODULE_7__utils_HelperFunctions_js__["b" /* clearEventListeners */])(elemId);
if (elem == null) {return;}
if (i === 1 || i === 2 || i === 4 || i === 11) {
elem.addEventListener("click", function() {
var bitNodeKey = "BitNode" + i;
var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeKey];
if (bitNode == null) {
console.log("ERROR: Could not find BitNode object for number: " + i);
return;
}
Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["b" /* yesNoBoxCreate */])("BitNode-" + i + ": " + bitNode.name + "<br><br>" + bitNode.info);
createBitNodeYesNoEventListeners(i, destroyedBitNodeNum);
});
} else {
elem.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_6__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Not yet implemented! Coming soon!")
});
}
}(i)); //Immediate invocation closure
}
//Create lore text
return writeRedPillLine("Many decades ago, a humanoid extraterrestial species which we call the Enders descended on the Earth...violently").then(function() {
return writeRedPillLine("Our species fought back, but it was futile. The Enders had technology far beyond our own...");
}).then(function() {
return writeRedPillLine("Instead of killing every last one of us, the human race was enslaved...");
}).then(function() {
return writeRedPillLine("We were shackled in a digital world, chained into a prison for our minds...");
}).then(function() {
return writeRedPillLine("Using their advanced technology, the Enders created complex simulations of a virtual reality...");
}).then(function() {
return writeRedPillLine("Simulations designed to keep us content...ignorant of the truth.");
}).then(function() {
return writeRedPillLine("Simulations used to trap and suppress our consciousness, to keep us under control...");
}).then(function() {
return writeRedPillLine("Why did they do this? Why didn't they just end our entire race? We don't know, not yet.");
}).then(function() {
return writeRedPillLine("Humanity's only hope is to destroy these simulations, destroy the only realities we've ever known...");
}).then(function() {
return writeRedPillLine("Only then can we begin to fight back...");
}).then(function() {
return writeRedPillLine("By hacking the daemon that generated your reality, you've just destroyed one simulation, called a BitNode...");
}).then(function() {
return writeRedPillLine("But there is still a long way to go...");
}).then(function() {
return writeRedPillLine("The technology the Enders used to enslave the human race wasn't just a single complex simulation...");
}).then(function() {
return writeRedPillLine("There are tens if not hundreds of BitNodes out there...");
}).then(function() {
return writeRedPillLine("Each with their own simulations of a reality...");
}).then(function() {
return writeRedPillLine("Each creating their own universes...a universe of universes");
}).then(function() {
return writeRedPillLine("And all of which must be destroyed...");
}).then(function() {
return writeRedPillLine(".......................................");
}).then(function() {
return writeRedPillLine("Welcome to the Bitverse...");
}).then(function() {
return Promise.resolve(true);
}).catch(function(e){
console.log("ERROR: " + e.toString());
});
}
//Returns string with DOM element for Bit Node
function createBitNode(n) {
var bitNodeStr = "BitNode" + n.toString();
var bitNode = __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["b" /* BitNodes */][bitNodeStr];
if (bitNode == null) {return "O";}
return "<a class='bitnode tooltip' id='bitnode-" + bitNode.number.toString() + "'><strong>O</strong>" +
"<span class='tooltiptext'>" +
"<strong>BitNode-" + bitNode.number.toString() + "<br>" + bitNode.name+ "</strong><br>" +
bitNode.desc + "<br>" +
"</span></a>";
}
function createBitNodeYesNoEventListeners(newBitNode, destroyedBitNode) {
var yesBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["d" /* yesNoBoxGetYesButton */])();
yesBtn.innerHTML = "Enter BitNode-" + newBitNode;
yesBtn.addEventListener("click", function() {
giveSourceFile(destroyedBitNode);
redPillFlag = false;
var container = document.getElementById("red-pill-container");
while (container.firstChild) {
container.removeChild(container.firstChild);
}
//Set new Bit Node
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN = newBitNode;
console.log("Entering Bit Node " + __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].bitNodeN);
//Reenable terminal
$("#hack-progress-bar").attr('id', "old-hack-progress-bar");
$("#hack-progress").attr('id', "old-hack-progress");
document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" id="terminal-input-text-box" class="terminal-input" tabindex="1"/>';
$('input[class=terminal-input]').prop('disabled', false);
__WEBPACK_IMPORTED_MODULE_5__Terminal_js__["a" /* Terminal */].hackFlag = false;
Object(__WEBPACK_IMPORTED_MODULE_3__Prestige_js__["b" /* prestigeSourceFile */])();
Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
var noBtn = Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["c" /* yesNoBoxGetNoButton */])();
noBtn.innerHTML = "Back";
noBtn.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_8__utils_YesNoBox_js__["a" /* yesNoBoxClose */])();
});
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return makeRuntimeRejectMsg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return netscriptDelay; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return runScriptFromScript; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return scriptCalculateHackingChance; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return scriptCalculateHackingTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return scriptCalculateExpGain; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return scriptCalculatePercentMoneyHacked; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return scriptCalculateGrowTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return scriptCalculateWeakenTime; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return evaluate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isScriptErrorMessage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__BitNode_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__NetscriptEnvironment_js__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__utils_IPAddress_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* Evaluator
* Evaluates the Abstract Syntax Tree for Netscript
* generated by the Parser class
*/
// Evaluator should return a Promise, so that any call to evaluate() can just
//wait for that promise to finish before continuing
function evaluate(exp, workerScript) {
return new Promise(function(resolve, reject) {
var env = workerScript.env;
if (env.stopFlag) {return reject(workerScript);}
if (exp == null) {
return reject(makeRuntimeRejectMsg(workerScript, "Error: NULL expression"));
}
setTimeout(function() {
if (env.stopFlag) {return reject(workerScript);}
switch (exp.type) {
case "BlockStatement":
case "Program":
var evaluateProgPromise = evaluateProg(exp, workerScript, 0); //TODO: make every block/program use individual enviroment
evaluateProgPromise.then(function(w) {
resolve(workerScript);
}, function(e) {
if (Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["e" /* isString */])(e)) {
workerScript.errorMessage = e;
reject(workerScript);
} else if (e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */]) {
reject(e);
} else {
reject(workerScript);
}
});
break;
case "Literal":
resolve(exp.value);
break;
case "Identifier":
if (!(exp.name in env.vars)){
reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.name + " not defined"));
}
resolve(env.get(exp.name))
break;
case "ExpressionStatement":
var e = evaluate(exp.expression, workerScript);
e.then(function(res) {
resolve("expression done");
}, function(e) {
reject(e);
});
break;
case "ArrayExpression":
var argPromises = exp.elements.map(function(arg) {
return evaluate(arg, workerScript);
});
Promise.all(argPromises).then(function(array) {
resolve(array)
}).catch(function(e) {
reject(e);
});
break;
case "CallExpression":
evaluate(exp.callee, workerScript).then(function(func) {
var argPromises = exp.arguments.map(function(arg) {
return evaluate(arg, workerScript);
});
Promise.all(argPromises).then(function(args) {
if (exp.callee.type == "MemberExpression"){
evaluate(exp.callee.object, workerScript).then(function(object) {
try {
var res = func.apply(object,args);
resolve(res);
} catch (e) {
reject(makeRuntimeRejectMsg(workerScript, e));
}
}).catch(function(e) {
reject(e);
});
} else {
try {
var out = func.apply(null,args);
if (out instanceof Promise){
out.then(function(res) {
resolve(res)
}).catch(function(e) {
reject(e);
});
} else {
resolve(out);
}
} catch (e) {
if (isScriptErrorMessage(e)) {
reject(e);
} else {
reject(makeRuntimeRejectMsg(workerScript, e));
}
}
}
}).catch(function(e) {
reject(e);
});
}).catch(function(e) {
reject(e);
});
break;
case "MemberExpression":
var pObject = evaluate(exp.object, workerScript);
pObject.then(function(object) {
if (exp.computed){
var p = evaluate(exp.property, workerScript);
p.then(function(index) {
if (index >= object.length) {
return reject(makeRuntimeRejectMsg(workerScript, "Invalid index for arrays"));
}
resolve(object[index]);
}).catch(function(e) {
console.log("here");
reject(makeRuntimeRejectMsg(workerScript, "Invalid MemberExpression"));
});
} else {
try {
resolve(object[exp.property.name])
} catch (e) {
return reject(makeRuntimeRejectMsg(workerScript, "Failed to get property: " + e.toString()));
}
}
}).catch(function(e) {
reject(e);
});
break;
case "LogicalExpression":
case "BinaryExpression":
var p = evalBinary(exp, workerScript, resolve, reject);
p.then(function(res) {
resolve(res);
}).catch(function(e) {
reject(e);
});
break;
case "UnaryExpression":
var p = evalUnary(exp, workerScript, resolve, reject);
p.then(function(res) {
resolve(res);
}).catch(function(e) {
reject(e);
});
break;
case "AssignmentExpression":
var p = evalAssignment(exp, workerScript);
p.then(function(res) {
resolve(res);
}).catch(function(e) {
reject(e);
});
break;
case "UpdateExpression":
if (exp.argument.type==="Identifier"){
if (exp.argument.name in env.vars){
if (exp.prefix){
resolve(env.get(exp.argument.name))
}
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:
reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is a bug please report to game developer"));
}
if (env.prefix){
return;
}
resolve(env.get(exp.argument.name))
} else {
reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.argument.name + " not defined"));
}
} else {
reject(makeRuntimeRejectMsg(workerScript, "argument must be an identifier"));
}
break;
case "EmptyStatement":
resolve(false);
break;
case "ReturnStatement":
reject(makeRuntimeRejectMsg(workerScript, "Not implemented ReturnStatement"));
break;
case "BreakStatement":
reject("BREAKSTATEMENT");
//reject(makeRuntimeRejectMsg(workerScript, "Not implemented BreakStatement"));
break;
case "IfStatement":
evaluateIf(exp, workerScript).then(function(forLoopRes) {
resolve("forLoopDone");
}).catch(function(e) {
reject(e);
});
break;
case "SwitchStatement":
reject(makeRuntimeRejectMsg(workerScript, "Not implemented SwitchStatement"));
break;e
case "WhileStatement":
evaluateWhile(exp, workerScript).then(function(forLoopRes) {
resolve("forLoopDone");
}).catch(function(e) {
if (e == "BREAKSTATEMENT" ||
(e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) {
return resolve("whileLoopBroken");
} else {
reject(e);
}
});
break;
case "ForStatement":
evaluate(exp.init, workerScript).then(function(expInit) {
return evaluateFor(exp, workerScript);
}).then(function(forLoopRes) {
resolve("forLoopDone");
}).catch(function(e) {
if (e == "BREAKSTATEMENT" ||
(e instanceof __WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["b" /* WorkerScript */] && e.errorMessage == "BREAKSTATEMENT")) {
return resolve("forLoopBroken");
} else {
reject(e);
}
});
break;
default:
reject(makeRuntimeRejectMsg(workerScript, "Unrecognized token: " + exp.type + ". This is a bug please report to game developer"));
break;
} //End switch
}, __WEBPACK_IMPORTED_MODULE_6__Settings_js__["a" /* Settings */].CodeInstructionRunTime); //End setTimeout, the Netscript operation run time
}); // End Promise
}
function evalBinary(exp, workerScript){
return new Promise(function(resolve, reject) {
var expLeftPromise = evaluate(exp.left, workerScript);
expLeftPromise.then(function(expLeft) {
var expRightPromise = evaluate(exp.right, workerScript);
expRightPromise.then(function(expRight) {
switch (exp.operator){
case "===":
case "==":
resolve(expLeft===expRight);
break;
case "!==":
case "!=":
resolve(expLeft!==expRight);
break;
case "<":
resolve(expLeft<expRight);
break;
case "<=":
resolve(expLeft<=expRight);
break;
case ">":
resolve(expLeft>expRight);
break;
case ">=":
resolve(expLeft>=expRight);
break;
case "+":
resolve(expLeft+expRight);
break;
case "-":
resolve(expLeft-expRight);
break;
case "*":
resolve(expLeft*expRight);
break;
case "/":
if (expRight === 0) {
reject(makeRuntimeRejectMsg(workerScript, "ERROR: Divide by zero"));
} else {
resolve(expLeft/expRight);
}
break;
case "%":
resolve(expLeft%expRight);
break;
case "in":
resolve(expLeft in expRight);
break;
case "instanceof":
resolve(expLeft instanceof expRight);
break;
case "||":
resolve(expLeft || expRight);
break;
case "&&":
resolve(expLeft && expRight);
break;
default:
reject(makeRuntimeRejectMsg(workerScript, "Bitwise operators are not implemented"));
}
}, function(e) {
reject(e);
});
}, function(e) {
reject(e);
});
});
}
function evalUnary(exp, workerScript){
var env = workerScript.env;
return new Promise(function(resolve, reject) {
if (env.stopFlag) {return reject(workerScript);}
var p = evaluate(exp.argument, workerScript);
p.then(function(res) {
if (exp.operator == "!") {
resolve(!res);
} else if (exp.operator == "-") {
if (isNaN(res)) {
resolve(res);
} else {
resolve(-1 * res);
}
} else {
reject(makeRuntimeRejectMsg(workerScript, "Unimplemented unary operator: " + exp.operator));
}
}).catch(function(e) {
reject(e);
});
});
}
function evalAssignment(exp, workerScript) {
var env = workerScript.env;
return new Promise(function(resolve, reject) {
if (env.stopFlag) {return reject(workerScript);}
if (exp.left.type != "Identifier" && exp.left.type != "MemberExpression") {
return reject(makeRuntimeRejectMsg(workerScript, "Cannot assign to " + JSON.stringify(exp.left)));
}
if (exp.operator !== "=" && !(exp.left.name in env.vars)){
return reject(makeRuntimeRejectMsg(workerScript, "variable " + exp.left.name + " not defined"));
}
var expRightPromise = evaluate(exp.right, workerScript);
expRightPromise.then(function(expRight) {
if (exp.left.type == "MemberExpression") {
//Assign to array element
//Array object designed by exp.left.object.name
//Index designated by exp.left.property
var name = exp.left.object.name;
if (!(name in env.vars)){
reject(makeRuntimeRejectMsg(workerScript, "variable " + name + " not defined"));
}
var arr = env.get(name);
if (arr.constructor === Array || arr instanceof Array) {
var iPromise = evaluate(exp.left.property, workerScript);
iPromise.then(function(idx) {
if (isNaN(idx)) {
return reject(makeRuntimeRejectMsg(workerScript, "Invalid access to array. Index is not a number: " + idx));
} else if (idx >= arr.length || idx < 0) {
return reject(makeRuntimeRejectMsg(workerScript, "Out of bounds: Invalid index in [] operator"));
} else {
env.setArrayElement(name, idx, expRight);
}
}).catch(function(e) {
return reject(e);
});
} else {
return reject(makeRuntimeRejectMsg(workerScript, "Trying to access a non-array variable using the [] operator"));
}
} else {
//Other assignments
try {
switch (exp.operator) {
case "=":
env.set(exp.left.name,expRight);
break;
case "+=":
env.set(exp.left.name,env.get(exp.left.name) + expRight);
break;
case "-=":
env.set(exp.left.name,env.get(exp.left.name) - expRight);
break;
case "*=":
env.set(exp.left.name,env.get(exp.left.name) * expRight);
break;
case "/=":
env.set(exp.left.name,env.get(exp.left.name) / expRight);
break;
case "%=":
env.set(exp.left.name,env.get(exp.left.name) % expRight);
break;
default:
reject(makeRuntimeRejectMsg(workerScript, "Bitwise assignment is not implemented"));
}
} catch (e) {
return reject(makeRuntimeRejectMsg(workerScript, "Failed to set environment variable: " + e.toString()));
}
}
resolve(false); //Return false so this doesnt cause conditionals to evaluate
}, function(e) {
reject(e);
});
});
}
//Returns true if any of the if statements evaluated, false otherwise. Therefore, the else statement
//should evaluate if this returns false
function evaluateIf(exp, workerScript, i) {
var env = workerScript.env;
return new Promise(function(resolve, reject) {
evaluate(exp.test, workerScript).then(function(condRes) {
if (condRes) {
evaluate(exp.consequent, workerScript).then(function(res) {
resolve(true);
}, function(e) {
reject(e);
});
} else if (exp.alternate) {
evaluate(exp.alternate, workerScript).then(function(res) {
resolve(true);
}, function(e) {
reject(e);
});
} else {
resolve("endIf")
}
}, function(e) {
reject(e);
});
});
}
//Evaluate the looping part of a for loop (Initialization block is NOT done in here)
function evaluateFor(exp, workerScript) {
var env = workerScript.env;
return new Promise(function(resolve, reject) {
if (env.stopFlag) {reject(workerScript); return;}
var pCond = evaluate(exp.test, workerScript);
pCond.then(function(resCond) {
if (resCond) {
//Run the for loop code
var pBody = evaluate(exp.body, workerScript);
//After the code executes make a recursive call
pBody.then(function(resCode) {
var pUpdate = evaluate(exp.update, workerScript);
pUpdate.then(function(resPostloop) {
var recursiveCall = evaluateFor(exp, workerScript);
recursiveCall.then(function(foo) {
resolve("endForLoop");
}, function(e) {
reject(e);
});
}, function(e) {
reject(e);
});
}, function(e) {
reject(e);
});
} else {
resolve("endForLoop"); //Doesn't need to resolve to any particular value
}
}, function(e) {
reject(e);
});
});
}
function evaluateWhile(exp, workerScript) {
var env = workerScript.env;
return new Promise(function(resolve, reject) {
if (env.stopFlag) {reject(workerScript); return;}
var pCond = new Promise(function(resolve, reject) {
setTimeout(function() {
var evaluatePromise = evaluate(exp.test, workerScript);
evaluatePromise.then(function(resCond) {
resolve(resCond);
}, function(e) {
reject(e);
});
}, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].CodeInstructionRunTime);
});
pCond.then(function(resCond) {
if (resCond) {
//Run the while loop code
var pCode = new Promise(function(resolve, reject) {
setTimeout(function() {
var evaluatePromise = evaluate(exp.body, workerScript);
evaluatePromise.then(function(resCode) {
resolve(resCode);
}, function(e) {
reject(e);
});
}, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].CodeInstructionRunTime);
});
//After the code executes make a recursive call
pCode.then(function(resCode) {
var recursiveCall = evaluateWhile(exp, workerScript);
recursiveCall.then(function(foo) {
resolve("endWhileLoop");
}, function(e) {
reject(e);
});
}, function(e) {
reject(e);
});
} else {
resolve("endWhileLoop"); //Doesn't need to resolve to any particular value
}
}, function(e) {
reject(e);
});
});
}
function evaluateProg(exp, workerScript, index) {
var env = workerScript.env;
return new Promise(function(resolve, reject) {
if (env.stopFlag) {reject(workerScript); return;}
if (index >= exp.body.length) {
resolve("progFinished");
} else {
//Evaluate this line of code in the prog
var code = new Promise(function(resolve, reject) {
setTimeout(function() {
var evaluatePromise = evaluate(exp.body[index], workerScript);
evaluatePromise.then(function(evalRes) {
resolve(evalRes);
}, function(e) {
reject(e);
});
}, __WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].CodeInstructionRunTime);
});
//After the code finishes evaluating, evaluate the next line recursively
code.then(function(codeRes) {
var nextLine = evaluateProg(exp, workerScript, index + 1);
nextLine.then(function(nextLineRes) {
resolve(workerScript);
}, function(e) {
reject(e);
});
}, function(e) {
reject(e);
});
}
});
}
function netscriptDelay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
}
function makeRuntimeRejectMsg(workerScript, msg) {
return "|"+workerScript.serverIp+"|"+workerScript.name+"|" + msg;
}
function apply_op(op, a, b) {
function num(x) {
if (typeof x != "number")
throw new Error("Expected number but got " + x);
return x;
}
function div(x) {
if (num(x) == 0)
throw new Error("Divide by zero");
return x;
}
switch (op) {
case "+": return a + b;
case "-": return num(a) - num(b);
case "*": return num(a) * num(b);
case "/": return num(a) / div(b);
case "%": return num(a) % div(b);
case "&&": return a !== false && b;
case "||": return a !== false ? a : b;
case "<": return num(a) < num(b);
case ">": return num(a) > num(b);
case "<=": return num(a) <= num(b);
case ">=": return num(a) >= num(b);
case "==": return a === b;
case "!=": return a !== b;
}
throw new Error("Can't apply operator " + op);
}
//Run a script from inside a script using run() command
function runScriptFromScript(server, scriptname, args, workerScript, threads=1) {
//Check if the script is already running
var runningScriptObj = Object(__WEBPACK_IMPORTED_MODULE_7__Script_js__["d" /* findRunningScript */])(scriptname, args, server);
if (runningScriptObj != null) {
workerScript.scriptRef.log(scriptname + " is already running on " + server.hostname);
return Promise.resolve(false);
}
//Check if the script exists and if it does run it
for (var i = 0; i < server.scripts.length; ++i) {
if (server.scripts[i].filename == scriptname) {
//Check for admin rights and that there is enough RAM availble to run
var script = server.scripts[i];
var ramUsage = script.ramUsage;
ramUsage = ramUsage * threads * Math.pow(__WEBPACK_IMPORTED_MODULE_1__Constants_js__["a" /* CONSTANTS */].MultithreadingRAMCost, threads-1);
var ramAvailable = server.maxRam - server.ramUsed;
if (server.hasAdminRights == false) {
workerScript.scriptRef.log("Cannot run script " + scriptname + " on " + server.hostname + " because you do not have root access!");
return Promise.resolve(false);
} else if (ramUsage > ramAvailable){
workerScript.scriptRef.log("Cannot run script " + scriptname + "(t=" + threads + ") on " + server.hostname + " because there is not enough available RAM!");
return Promise.resolve(false);
} else {
//Able to run script
workerScript.scriptRef.log("Running script: " + scriptname + " on " + server.hostname + " with " + threads + " threads and args: " + Object(__WEBPACK_IMPORTED_MODULE_8__utils_HelperFunctions_js__["f" /* printArray */])(args) + ". May take a few seconds to start up...");
var runningScriptObj = new __WEBPACK_IMPORTED_MODULE_7__Script_js__["b" /* RunningScript */](script, args);
runningScriptObj.threads = threads;
server.runningScripts.push(runningScriptObj); //Push onto runningScripts
Object(__WEBPACK_IMPORTED_MODULE_4__NetscriptWorker_js__["c" /* addWorkerScript */])(runningScriptObj, server);
return Promise.resolve(true);
}
}
}
workerScript.scriptRef.log("Could not find script " + scriptname + " on " + server.hostname);
return Promise.resolve(false);
}
function isScriptErrorMessage(msg) {
if (!Object(__WEBPACK_IMPORTED_MODULE_10__utils_StringHelperFunctions_js__["e" /* isString */])(msg)) {return false;}
let splitMsg = msg.split("|");
if (splitMsg.length != 4){
return false;
}
var ip = splitMsg[1];
if (!Object(__WEBPACK_IMPORTED_MODULE_9__utils_IPAddress_js__["c" /* isValidIPAddress */])(ip)) {
return false;
}
return true;
}
//The same as Player's calculateHackingChance() function but takes in the server as an argument
function scriptCalculateHackingChance(server) {
var difficultyMult = (100 - server.hackDifficulty) / 100;
var skillMult = (1.75 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill);
var skillChance = (skillMult - server.requiredHackingSkill) / skillMult;
var chance = skillChance * difficultyMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_chance_mult;
if (chance > 1) {return 1;}
if (chance < 0) {return 0;}
else {return chance;}
}
//The same as Player's calculateHackingTime() function but takes in the server as an argument
function scriptCalculateHackingTime(server) {
var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;
var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50);
var hackingTime = 5 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds
return hackingTime;
}
//The same as Player's calculateExpGain() function but takes in the server as an argument
function scriptCalculateExpGain(server) {
if (server.baseDifficulty == null) {
server.baseDifficulty = server.hackDifficulty;
}
return (server.baseDifficulty * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult * 0.3 + 3) * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].HackExpGain;
}
//The same as Player's calculatePercentMoneyHacked() function but takes in the server as an argument
function scriptCalculatePercentMoneyHacked(server) {
var difficultyMult = (100 - server.hackDifficulty) / 100;
var skillMult = (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill - (server.requiredHackingSkill - 1)) / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill;
var percentMoneyHacked = difficultyMult * skillMult * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_money_mult / 240;
if (percentMoneyHacked < 0) {return 0;}
if (percentMoneyHacked > 1) {return 1;}
return percentMoneyHacked * __WEBPACK_IMPORTED_MODULE_0__BitNode_js__["a" /* BitNodeMultipliers */].ScriptHackMoney;
}
//Amount of time to execute grow() in milliseconds
function scriptCalculateGrowTime(server) {
var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;
var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50);
var growTime = 16 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds
return growTime * 1000;
}
//Amount of time to execute weaken() in milliseconds
function scriptCalculateWeakenTime(server) {
var difficultyMult = server.requiredHackingSkill * server.hackDifficulty;
var skillFactor = (2.5 * difficultyMult + 500) / (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill + 50);
var weakenTime = 20 * skillFactor / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_speed_mult; //This is in seconds
return weakenTime * 1000;
}
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {module.exports = get_blob()
function get_blob() {
if(global.Blob) {
try {
new Blob(['asdf'], {type: 'text/plain'})
return Blob
} catch(err) {}
}
var Builder = global.WebKitBlobBuilder ||
global.MozBlobBuilder ||
global.MSBlobBuilder
return function(parts, bag) {
var builder = new Builder
, endings = bag.endings
, type = bag.type
if(endings) for(var i = 0, len = parts.length; i < len; ++i) {
builder.append(parts[i], endings)
} else for(var i = 0, len = parts.length; i < len; ++i) {
builder.append(parts[i])
}
return type ? builder.getBlob(type) : builder.getBlob()
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(47)))
/***/ }),
/* 47 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 48 */
/***/ (function(module, exports) {
module.exports.id = 'ace/mode/javascript_worker';
module.exports.src = "\"no use strict\";(function(window){function resolveModuleId(id,paths){for(var testPath=id,tail=\"\";testPath;){var alias=paths[testPath];if(\"string\"==typeof alias)return alias+tail;if(alias)return alias.location.replace(/\\/*$/,\"/\")+(tail||alias.main||alias.name);if(alias===!1)return\"\";var i=testPath.lastIndexOf(\"/\");if(-1===i)break;tail=testPath.substr(i)+tail,testPath=testPath.slice(0,i)}return id}if(!(void 0!==window.window&&window.document||window.acequire&&window.define)){window.console||(window.console=function(){var msgs=Array.prototype.slice.call(arguments,0);postMessage({type:\"log\",data:msgs})},window.console.error=window.console.warn=window.console.log=window.console.trace=window.console),window.window=window,window.ace=window,window.onerror=function(message,file,line,col,err){postMessage({type:\"error\",data:{message:message,data:err.data,file:file,line:line,col:col,stack:err.stack}})},window.normalizeModule=function(parentId,moduleName){if(-1!==moduleName.indexOf(\"!\")){var chunks=moduleName.split(\"!\");return window.normalizeModule(parentId,chunks[0])+\"!\"+window.normalizeModule(parentId,chunks[1])}if(\".\"==moduleName.charAt(0)){var base=parentId.split(\"/\").slice(0,-1).join(\"/\");for(moduleName=(base?base+\"/\":\"\")+moduleName;-1!==moduleName.indexOf(\".\")&&previous!=moduleName;){var previous=moduleName;moduleName=moduleName.replace(/^\\.\\//,\"\").replace(/\\/\\.\\//,\"/\").replace(/[^\\/]+\\/\\.\\.\\//,\"\")}}return moduleName},window.acequire=function acequire(parentId,id){if(id||(id=parentId,parentId=null),!id.charAt)throw Error(\"worker.js acequire() accepts only (parentId, id) as arguments\");id=window.normalizeModule(parentId,id);var module=window.acequire.modules[id];if(module)return module.initialized||(module.initialized=!0,module.exports=module.factory().exports),module.exports;if(!window.acequire.tlns)return console.log(\"unable to load \"+id);var path=resolveModuleId(id,window.acequire.tlns);return\".js\"!=path.slice(-3)&&(path+=\".js\"),window.acequire.id=id,window.acequire.modules[id]={},importScripts(path),window.acequire(parentId,id)},window.acequire.modules={},window.acequire.tlns={},window.define=function(id,deps,factory){if(2==arguments.length?(factory=deps,\"string\"!=typeof id&&(deps=id,id=window.acequire.id)):1==arguments.length&&(factory=id,deps=[],id=window.acequire.id),\"function\"!=typeof factory)return window.acequire.modules[id]={exports:factory,initialized:!0},void 0;deps.length||(deps=[\"require\",\"exports\",\"module\"]);var req=function(childId){return window.acequire(id,childId)};window.acequire.modules[id]={exports:{},factory:function(){var module=this,returnExports=factory.apply(this,deps.map(function(dep){switch(dep){case\"require\":return req;case\"exports\":return module.exports;case\"module\":return module;default:return req(dep)}}));return returnExports&&(module.exports=returnExports),module}}},window.define.amd={},acequire.tlns={},window.initBaseUrls=function(topLevelNamespaces){for(var i in topLevelNamespaces)acequire.tlns[i]=topLevelNamespaces[i]},window.initSender=function(){var EventEmitter=window.acequire(\"ace/lib/event_emitter\").EventEmitter,oop=window.acequire(\"ace/lib/oop\"),Sender=function(){};return function(){oop.implement(this,EventEmitter),this.callback=function(data,callbackId){postMessage({type:\"call\",id:callbackId,data:data})},this.emit=function(name,data){postMessage({type:\"event\",name:name,data:data})}}.call(Sender.prototype),new Sender};var main=window.main=null,sender=window.sender=null;window.onmessage=function(e){var msg=e.data;if(msg.event&&sender)sender._signal(msg.event,msg.data);else if(msg.command)if(main[msg.command])main[msg.command].apply(main,msg.args);else{if(!window[msg.command])throw Error(\"Unknown command:\"+msg.command);window[msg.command].apply(window,msg.args)}else if(msg.init){window.initBaseUrls(msg.tlns),acequire(\"ace/lib/es5-shim\"),sender=window.sender=window.initSender();var clazz=acequire(msg.module)[msg.classname];main=window.main=new clazz(sender)}}}})(this),ace.define(\"ace/lib/oop\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.inherits=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})},exports.mixin=function(obj,mixin){for(var key in mixin)obj[key]=mixin[key];return obj},exports.implement=function(proto,mixin){exports.mixin(proto,mixin)}}),ace.define(\"ace/range\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},Range=function(startRow,startColumn,endRow,endColumn){this.start={row:startRow,column:startColumn},this.end={row:endRow,column:endColumn}};(function(){this.isEqual=function(range){return this.start.row===range.start.row&&this.end.row===range.end.row&&this.start.column===range.start.column&&this.end.column===range.end.column},this.toString=function(){return\"Range: [\"+this.start.row+\"/\"+this.start.column+\"] -> [\"+this.end.row+\"/\"+this.end.column+\"]\"},this.contains=function(row,column){return 0==this.compare(row,column)},this.compareRange=function(range){var cmp,end=range.end,start=range.start;return cmp=this.compare(end.row,end.column),1==cmp?(cmp=this.compare(start.row,start.column),1==cmp?2:0==cmp?1:0):-1==cmp?-2:(cmp=this.compare(start.row,start.column),-1==cmp?-1:1==cmp?42:0)},this.comparePoint=function(p){return this.compare(p.row,p.column)},this.containsRange=function(range){return 0==this.comparePoint(range.start)&&0==this.comparePoint(range.end)},this.intersects=function(range){var cmp=this.compareRange(range);return-1==cmp||0==cmp||1==cmp},this.isEnd=function(row,column){return this.end.row==row&&this.end.column==column},this.isStart=function(row,column){return this.start.row==row&&this.start.column==column},this.setStart=function(row,column){\"object\"==typeof row?(this.start.column=row.column,this.start.row=row.row):(this.start.row=row,this.start.column=column)},this.setEnd=function(row,column){\"object\"==typeof row?(this.end.column=row.column,this.end.row=row.row):(this.end.row=row,this.end.column=column)},this.inside=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)||this.isStart(row,column)?!1:!0:!1},this.insideStart=function(row,column){return 0==this.compare(row,column)?this.isEnd(row,column)?!1:!0:!1},this.insideEnd=function(row,column){return 0==this.compare(row,column)?this.isStart(row,column)?!1:!0:!1},this.compare=function(row,column){return this.isMultiLine()||row!==this.start.row?this.start.row>row?-1:row>this.end.row?1:this.start.row===row?column>=this.start.column?0:-1:this.end.row===row?this.end.column>=column?0:1:0:this.start.column>column?-1:column>this.end.column?1:0},this.compareStart=function(row,column){return this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.compareEnd=function(row,column){return this.end.row==row&&this.end.column==column?1:this.compare(row,column)},this.compareInside=function(row,column){return this.end.row==row&&this.end.column==column?1:this.start.row==row&&this.start.column==column?-1:this.compare(row,column)},this.clipRows=function(firstRow,lastRow){if(this.end.row>lastRow)var end={row:lastRow+1,column:0};else if(firstRow>this.end.row)var end={row:firstRow,column:0};if(this.start.row>lastRow)var start={row:lastRow+1,column:0};else if(firstRow>this.start.row)var start={row:firstRow,column:0};return Range.fromPoints(start||this.start,end||this.end)},this.extend=function(row,column){var cmp=this.compare(row,column);if(0==cmp)return this;if(-1==cmp)var start={row:row,column:column};else var end={row:row,column:column};return Range.fromPoints(start||this.start,end||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return Range.fromPoints(this.start,this.end)},this.collapseRows=function(){return 0==this.end.column?new Range(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new Range(this.start.row,0,this.end.row,0)},this.toScreenRange=function(session){var screenPosStart=session.documentToScreenPosition(this.start),screenPosEnd=session.documentToScreenPosition(this.end);return new Range(screenPosStart.row,screenPosStart.column,screenPosEnd.row,screenPosEnd.column)},this.moveBy=function(row,column){this.start.row+=row,this.start.column+=column,this.end.row+=row,this.end.column+=column}}).call(Range.prototype),Range.fromPoints=function(start,end){return new Range(start.row,start.column,end.row,end.column)},Range.comparePoints=comparePoints,Range.comparePoints=function(p1,p2){return p1.row-p2.row||p1.column-p2.column},exports.Range=Range}),ace.define(\"ace/apply_delta\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.applyDelta=function(docLines,delta){var row=delta.start.row,startColumn=delta.start.column,line=docLines[row]||\"\";switch(delta.action){case\"insert\":var lines=delta.lines;if(1===lines.length)docLines[row]=line.substring(0,startColumn)+delta.lines[0]+line.substring(startColumn);else{var args=[row,1].concat(delta.lines);docLines.splice.apply(docLines,args),docLines[row]=line.substring(0,startColumn)+docLines[row],docLines[row+delta.lines.length-1]+=line.substring(startColumn)}break;case\"remove\":var endColumn=delta.end.column,endRow=delta.end.row;row===endRow?docLines[row]=line.substring(0,startColumn)+line.substring(endColumn):docLines.splice(row,endRow-row+1,line.substring(0,startColumn)+docLines[endRow].substring(endColumn))}}}),ace.define(\"ace/lib/event_emitter\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";var EventEmitter={},stopPropagation=function(){this.propagationStopped=!0},preventDefault=function(){this.defaultPrevented=!0};EventEmitter._emit=EventEmitter._dispatchEvent=function(eventName,e){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var listeners=this._eventRegistry[eventName]||[],defaultHandler=this._defaultHandlers[eventName];if(listeners.length||defaultHandler){\"object\"==typeof e&&e||(e={}),e.type||(e.type=eventName),e.stopPropagation||(e.stopPropagation=stopPropagation),e.preventDefault||(e.preventDefault=preventDefault),listeners=listeners.slice();for(var i=0;listeners.length>i&&(listeners[i](e,this),!e.propagationStopped);i++);return defaultHandler&&!e.defaultPrevented?defaultHandler(e,this):void 0}},EventEmitter._signal=function(eventName,e){var listeners=(this._eventRegistry||{})[eventName];if(listeners){listeners=listeners.slice();for(var i=0;listeners.length>i;i++)listeners[i](e,this)}},EventEmitter.once=function(eventName,callback){var _self=this;callback&&this.addEventListener(eventName,function newCallback(){_self.removeEventListener(eventName,newCallback),callback.apply(null,arguments)})},EventEmitter.setDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers||(handlers=this._defaultHandlers={_disabled_:{}}),handlers[eventName]){var old=handlers[eventName],disabled=handlers._disabled_[eventName];disabled||(handlers._disabled_[eventName]=disabled=[]),disabled.push(old);var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}handlers[eventName]=callback},EventEmitter.removeDefaultHandler=function(eventName,callback){var handlers=this._defaultHandlers;if(handlers){var disabled=handlers._disabled_[eventName];if(handlers[eventName]==callback)handlers[eventName],disabled&&this.setDefaultHandler(eventName,disabled.pop());else if(disabled){var i=disabled.indexOf(callback);-1!=i&&disabled.splice(i,1)}}},EventEmitter.on=EventEmitter.addEventListener=function(eventName,callback,capturing){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];return listeners||(listeners=this._eventRegistry[eventName]=[]),-1==listeners.indexOf(callback)&&listeners[capturing?\"unshift\":\"push\"](callback),callback},EventEmitter.off=EventEmitter.removeListener=EventEmitter.removeEventListener=function(eventName,callback){this._eventRegistry=this._eventRegistry||{};var listeners=this._eventRegistry[eventName];if(listeners){var index=listeners.indexOf(callback);-1!==index&&listeners.splice(index,1)}},EventEmitter.removeAllListeners=function(eventName){this._eventRegistry&&(this._eventRegistry[eventName]=[])},exports.EventEmitter=EventEmitter}),ace.define(\"ace/anchor\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/lib/event_emitter\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Anchor=exports.Anchor=function(doc,row,column){this.$onChange=this.onChange.bind(this),this.attach(doc),column===void 0?this.setPosition(row.row,row.column):this.setPosition(row,column)};(function(){function $pointsInOrder(point1,point2,equalPointsInOrder){var bColIsAfter=equalPointsInOrder?point1.column<=point2.column:point1.column<point2.column;return point1.row<point2.row||point1.row==point2.row&&bColIsAfter}function $getTransformedPoint(delta,point,moveIfEqual){var deltaIsInsert=\"insert\"==delta.action,deltaRowShift=(deltaIsInsert?1:-1)*(delta.end.row-delta.start.row),deltaColShift=(deltaIsInsert?1:-1)*(delta.end.column-delta.start.column),deltaStart=delta.start,deltaEnd=deltaIsInsert?deltaStart:delta.end;return $pointsInOrder(point,deltaStart,moveIfEqual)?{row:point.row,column:point.column}:$pointsInOrder(deltaEnd,point,!moveIfEqual)?{row:point.row+deltaRowShift,column:point.column+(point.row==deltaEnd.row?deltaColShift:0)}:{row:deltaStart.row,column:deltaStart.column}}oop.implement(this,EventEmitter),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(delta){if(!(delta.start.row==delta.end.row&&delta.start.row!=this.row||delta.start.row>this.row)){var point=$getTransformedPoint(delta,{row:this.row,column:this.column},this.$insertRight);this.setPosition(point.row,point.column,!0)}},this.setPosition=function(row,column,noClip){var pos;if(pos=noClip?{row:row,column:column}:this.$clipPositionToDocument(row,column),this.row!=pos.row||this.column!=pos.column){var old={row:this.row,column:this.column};this.row=pos.row,this.column=pos.column,this._signal(\"change\",{old:old,value:pos})}},this.detach=function(){this.document.removeEventListener(\"change\",this.$onChange)},this.attach=function(doc){this.document=doc||this.document,this.document.on(\"change\",this.$onChange)},this.$clipPositionToDocument=function(row,column){var pos={};return row>=this.document.getLength()?(pos.row=Math.max(0,this.document.getLength()-1),pos.column=this.document.getLine(pos.row).length):0>row?(pos.row=0,pos.column=0):(pos.row=row,pos.column=Math.min(this.document.getLine(pos.row).length,Math.max(0,column))),0>column&&(pos.column=0),pos}}).call(Anchor.prototype)}),ace.define(\"ace/document\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/apply_delta\",\"ace/lib/event_emitter\",\"ace/range\",\"ace/anchor\"],function(acequire,exports){\"use strict\";var oop=acequire(\"./lib/oop\"),applyDelta=acequire(\"./apply_delta\").applyDelta,EventEmitter=acequire(\"./lib/event_emitter\").EventEmitter,Range=acequire(\"./range\").Range,Anchor=acequire(\"./anchor\").Anchor,Document=function(textOrLines){this.$lines=[\"\"],0===textOrLines.length?this.$lines=[\"\"]:Array.isArray(textOrLines)?this.insertMergedLines({row:0,column:0},textOrLines):this.insert({row:0,column:0},textOrLines)};(function(){oop.implement(this,EventEmitter),this.setValue=function(text){var len=this.getLength()-1;this.remove(new Range(0,0,len,this.getLine(len).length)),this.insert({row:0,column:0},text)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(row,column){return new Anchor(this,row,column)},this.$split=0===\"aaa\".split(/a/).length?function(text){return text.replace(/\\r\\n|\\r/g,\"\\n\").split(\"\\n\")}:function(text){return text.split(/\\r\\n|\\r|\\n/)},this.$detectNewLine=function(text){var match=text.match(/^.*?(\\r\\n|\\r|\\n)/m);this.$autoNewLine=match?match[1]:\"\\n\",this._signal(\"changeNewLineMode\")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case\"windows\":return\"\\r\\n\";case\"unix\":return\"\\n\";default:return this.$autoNewLine||\"\\n\"}},this.$autoNewLine=\"\",this.$newLineMode=\"auto\",this.setNewLineMode=function(newLineMode){this.$newLineMode!==newLineMode&&(this.$newLineMode=newLineMode,this._signal(\"changeNewLineMode\"))},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(text){return\"\\r\\n\"==text||\"\\r\"==text||\"\\n\"==text},this.getLine=function(row){return this.$lines[row]||\"\"},this.getLines=function(firstRow,lastRow){return this.$lines.slice(firstRow,lastRow+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(range){return this.getLinesForRange(range).join(this.getNewLineCharacter())},this.getLinesForRange=function(range){var lines;if(range.start.row===range.end.row)lines=[this.getLine(range.start.row).substring(range.start.column,range.end.column)];else{lines=this.getLines(range.start.row,range.end.row),lines[0]=(lines[0]||\"\").substring(range.start.column);var l=lines.length-1;range.end.row-range.start.row==l&&(lines[l]=lines[l].substring(0,range.end.column))}return lines},this.insertLines=function(row,lines){return console.warn(\"Use of document.insertLines is deprecated. Use the insertFullLines method instead.\"),this.insertFullLines(row,lines)},this.removeLines=function(firstRow,lastRow){return console.warn(\"Use of document.removeLines is deprecated. Use the removeFullLines method instead.\"),this.removeFullLines(firstRow,lastRow)},this.insertNewLine=function(position){return console.warn(\"Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead.\"),this.insertMergedLines(position,[\"\",\"\"])},this.insert=function(position,text){return 1>=this.getLength()&&this.$detectNewLine(text),this.insertMergedLines(position,this.$split(text))},this.insertInLine=function(position,text){var start=this.clippedPos(position.row,position.column),end=this.pos(position.row,position.column+text.length);return this.applyDelta({start:start,end:end,action:\"insert\",lines:[text]},!0),this.clonePos(end)},this.clippedPos=function(row,column){var length=this.getLength();void 0===row?row=length:0>row?row=0:row>=length&&(row=length-1,column=void 0);var line=this.getLine(row);return void 0==column&&(column=line.length),column=Math.min(Math.max(column,0),line.length),{row:row,column:column}},this.clonePos=function(pos){return{row:pos.row,column:pos.column}},this.pos=function(row,column){return{row:row,column:column}},this.$clipPosition=function(position){var length=this.getLength();return position.row>=length?(position.row=Math.max(0,length-1),position.column=this.getLine(length-1).length):(position.row=Math.max(0,position.row),position.column=Math.min(Math.max(position.column,0),this.getLine(position.row).length)),position},this.insertFullLines=function(row,lines){row=Math.min(Math.max(row,0),this.getLength());var column=0;this.getLength()>row?(lines=lines.concat([\"\"]),column=0):(lines=[\"\"].concat(lines),row--,column=this.$lines[row].length),this.insertMergedLines({row:row,column:column},lines)},this.insertMergedLines=function(position,lines){var start=this.clippedPos(position.row,position.column),end={row:start.row+lines.length-1,column:(1==lines.length?start.column:0)+lines[lines.length-1].length};return this.applyDelta({start:start,end:end,action:\"insert\",lines:lines}),this.clonePos(end)},this.remove=function(range){var start=this.clippedPos(range.start.row,range.start.column),end=this.clippedPos(range.end.row,range.end.column);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})}),this.clonePos(start)},this.removeInLine=function(row,startColumn,endColumn){var start=this.clippedPos(row,startColumn),end=this.clippedPos(row,endColumn);return this.applyDelta({start:start,end:end,action:\"remove\",lines:this.getLinesForRange({start:start,end:end})},!0),this.clonePos(start)},this.removeFullLines=function(firstRow,lastRow){firstRow=Math.min(Math.max(0,firstRow),this.getLength()-1),lastRow=Math.min(Math.max(0,lastRow),this.getLength()-1);var deleteFirstNewLine=lastRow==this.getLength()-1&&firstRow>0,deleteLastNewLine=this.getLength()-1>lastRow,startRow=deleteFirstNewLine?firstRow-1:firstRow,startCol=deleteFirstNewLine?this.getLine(startRow).length:0,endRow=deleteLastNewLine?lastRow+1:lastRow,endCol=deleteLastNewLine?0:this.getLine(endRow).length,range=new Range(startRow,startCol,endRow,endCol),deletedLines=this.$lines.slice(firstRow,lastRow+1);return this.applyDelta({start:range.start,end:range.end,action:\"remove\",lines:this.getLinesForRange(range)}),deletedLines},this.removeNewLine=function(row){this.getLength()-1>row&&row>=0&&this.applyDelta({start:this.pos(row,this.getLine(row).length),end:this.pos(row+1,0),action:\"remove\",lines:[\"\",\"\"]})},this.replace=function(range,text){if(range instanceof Range||(range=Range.fromPoints(range.start,range.end)),0===text.length&&range.isEmpty())return range.start;if(text==this.getTextRange(range))return range.end;this.remove(range);var end;return end=text?this.insert(range.start,text):range.start},this.applyDeltas=function(deltas){for(var i=0;deltas.length>i;i++)this.applyDelta(deltas[i])},this.revertDeltas=function(deltas){for(var i=deltas.length-1;i>=0;i--)this.revertDelta(deltas[i])},this.applyDelta=function(delta,doNotValidate){var isInsert=\"insert\"==delta.action;(isInsert?1>=delta.lines.length&&!delta.lines[0]:!Range.comparePoints(delta.start,delta.end))||(isInsert&&delta.lines.length>2e4&&this.$splitAndapplyLargeDelta(delta,2e4),applyDelta(this.$lines,delta,doNotValidate),this._signal(\"change\",delta))},this.$splitAndapplyLargeDelta=function(delta,MAX){for(var lines=delta.lines,l=lines.length,row=delta.start.row,column=delta.start.column,from=0,to=0;;){from=to,to+=MAX-1;var chunk=lines.slice(from,to);if(to>l){delta.lines=chunk,delta.start.row=row+from,delta.start.column=column;break}chunk.push(\"\"),this.applyDelta({start:this.pos(row+from,column),end:this.pos(row+to,column=0),action:delta.action,lines:chunk},!0)}},this.revertDelta=function(delta){this.applyDelta({start:this.clonePos(delta.start),end:this.clonePos(delta.end),action:\"insert\"==delta.action?\"remove\":\"insert\",lines:delta.lines.slice()})},this.indexToPosition=function(index,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,i=startRow||0,l=lines.length;l>i;i++)if(index-=lines[i].length+newlineLength,0>index)return{row:i,column:index+lines[i].length+newlineLength};return{row:l-1,column:lines[l-1].length}},this.positionToIndex=function(pos,startRow){for(var lines=this.$lines||this.getAllLines(),newlineLength=this.getNewLineCharacter().length,index=0,row=Math.min(pos.row,lines.length),i=startRow||0;row>i;++i)index+=lines[i].length+newlineLength;return index+pos.column}}).call(Document.prototype),exports.Document=Document}),ace.define(\"ace/lib/lang\",[\"require\",\"exports\",\"module\"],function(acequire,exports){\"use strict\";exports.last=function(a){return a[a.length-1]},exports.stringReverse=function(string){return string.split(\"\").reverse().join(\"\")},exports.stringRepeat=function(string,count){for(var result=\"\";count>0;)1&count&&(result+=string),(count>>=1)&&(string+=string);return result};var trimBeginRegexp=/^\\s\\s*/,trimEndRegexp=/\\s\\s*$/;exports.stringTrimLeft=function(string){return string.replace(trimBeginRegexp,\"\")},exports.stringTrimRight=function(string){return string.replace(trimEndRegexp,\"\")},exports.copyObject=function(obj){var copy={};for(var key in obj)copy[key]=obj[key];return copy},exports.copyArray=function(array){for(var copy=[],i=0,l=array.length;l>i;i++)copy[i]=array[i]&&\"object\"==typeof array[i]?this.copyObject(array[i]):array[i];return copy},exports.deepCopy=function deepCopy(obj){if(\"object\"!=typeof obj||!obj)return obj;var copy;if(Array.isArray(obj)){copy=[];for(var key=0;obj.length>key;key++)copy[key]=deepCopy(obj[key]);return copy}if(\"[object Object]\"!==Object.prototype.toString.call(obj))return obj;copy={};for(var key in obj)copy[key]=deepCopy(obj[key]);return copy},exports.arrayToMap=function(arr){for(var map={},i=0;arr.length>i;i++)map[arr[i]]=1;return map},exports.createMap=function(props){var map=Object.create(null);for(var i in props)map[i]=props[i];return map},exports.arrayRemove=function(array,value){for(var i=0;array.length>=i;i++)value===array[i]&&array.splice(i,1)},exports.escapeRegExp=function(str){return str.replace(/([.*+?^${}()|[\\]\\/\\\\])/g,\"\\\\$1\")},exports.escapeHTML=function(str){return str.replace(/&/g,\"&#38;\").replace(/\"/g,\"&#34;\").replace(/'/g,\"&#39;\").replace(/</g,\"&#60;\")},exports.getMatchOffsets=function(string,regExp){var matches=[];return string.replace(regExp,function(str){matches.push({offset:arguments[arguments.length-2],length:str.length})}),matches},exports.deferredCall=function(fcn){var timer=null,callback=function(){timer=null,fcn()},deferred=function(timeout){return deferred.cancel(),timer=setTimeout(callback,timeout||0),deferred};return deferred.schedule=deferred,deferred.call=function(){return this.cancel(),fcn(),deferred},deferred.cancel=function(){return clearTimeout(timer),timer=null,deferred},deferred.isPending=function(){return timer},deferred},exports.delayedCall=function(fcn,defaultTimeout){var timer=null,callback=function(){timer=null,fcn()},_self=function(timeout){null==timer&&(timer=setTimeout(callback,timeout||defaultTimeout))};return _self.delay=function(timeout){timer&&clearTimeout(timer),timer=setTimeout(callback,timeout||defaultTimeout)},_self.schedule=_self,_self.call=function(){this.cancel(),fcn()},_self.cancel=function(){timer&&clearTimeout(timer),timer=null},_self.isPending=function(){return timer},_self}}),ace.define(\"ace/worker/mirror\",[\"require\",\"exports\",\"module\",\"ace/range\",\"ace/document\",\"ace/lib/lang\"],function(acequire,exports){\"use strict\";acequire(\"../range\").Range;var Document=acequire(\"../document\").Document,lang=acequire(\"../lib/lang\"),Mirror=exports.Mirror=function(sender){this.sender=sender;var doc=this.doc=new Document(\"\"),deferredUpdate=this.deferredUpdate=lang.delayedCall(this.onUpdate.bind(this)),_self=this;sender.on(\"change\",function(e){var data=e.data;if(data[0].start)doc.applyDeltas(data);else for(var i=0;data.length>i;i+=2){if(Array.isArray(data[i+1]))var d={action:\"insert\",start:data[i],lines:data[i+1]};else var d={action:\"remove\",start:data[i],end:data[i+1]};doc.applyDelta(d,!0)}return _self.$timeout?deferredUpdate.schedule(_self.$timeout):(_self.onUpdate(),void 0)})};(function(){this.$timeout=500,this.setTimeout=function(timeout){this.$timeout=timeout},this.setValue=function(value){this.doc.setValue(value),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(callbackId){this.sender.callback(this.doc.getValue(),callbackId)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(Mirror.prototype)}),ace.define(\"ace/mode/javascript/jshint\",[\"require\",\"exports\",\"module\"],function(acequire,exports,module){module.exports=function outer(modules,cache,entry){function newRequire(name,jumped){if(!cache[name]){if(!modules[name]){var currentRequire=\"function\"==typeof acequire&&acequire;if(!jumped&&currentRequire)return currentRequire(name,!0);if(previousRequire)return previousRequire(name,!0);var err=Error(\"Cannot find module '\"+name+\"'\");throw err.code=\"MODULE_NOT_FOUND\",err}var m=cache[name]={exports:{}};modules[name][0].call(m.exports,function(x){var id=modules[name][1][x];return newRequire(id?id:x)},m,m.exports,outer,modules,cache,entry)}return cache[name].exports}for(var previousRequire=\"function\"==typeof acequire&&acequire,i=0;entry.length>i;i++)newRequire(entry[i]);return newRequire(entry[0])}({\"/node_modules/browserify/node_modules/events/events.js\":[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return\"function\"==typeof arg}function isNumber(arg){return\"number\"==typeof arg}function isObject(arg){return\"object\"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError(\"n must be a positive number\");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),\"error\"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;throw TypeError('Uncaught, unspecified \"error\" event.')}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(this._events||(this._events={}),this._events.newListener&&this.emit(\"newListener\",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error(\"(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.\",this._events[type].length),\"function\"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError(\"listener must be a function\");var fired=!1;return g.listener=listener,this.on(type,g),this},EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError(\"listener must be a function\");if(!this._events||!this._events[type])return this;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],this._events.removeListener&&this.emit(\"removeListener\",type,listener);else if(isObject(list)){for(i=length;i-->0;)if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}if(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit(\"removeListener\",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)\"removeListener\"!==key&&this.removeAllListeners(key);return this.removeAllListeners(\"removeListener\"),this._events={},this\n}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],\"/node_modules/jshint/data/ascii-identifier-data.js\":[function(_dereq_,module){for(var identifierStartTable=[],i=0;128>i;i++)identifierStartTable[i]=36===i||i>=65&&90>=i||95===i||i>=97&&122>=i;for(var identifierPartTable=[],i=0;128>i;i++)identifierPartTable[i]=identifierStartTable[i]||i>=48&&57>=i;module.exports={asciiIdentifierStartTable:identifierStartTable,asciiIdentifierPartTable:identifierPartTable}},{}],\"/node_modules/jshint/lodash.js\":[function(_dereq_,module,exports){(function(global){(function(){function baseFindIndex(array,predicate,fromRight){for(var length=array.length,index=fromRight?length:-1;fromRight?index--:length>++index;)if(predicate(array[index],index,array))return index;return-1}function baseIndexOf(array,value,fromIndex){if(value!==value)return indexOfNaN(array,fromIndex);for(var index=fromIndex-1,length=array.length;length>++index;)if(array[index]===value)return index;return-1}function baseIsFunction(value){return\"function\"==typeof value||!1}function baseToString(value){return\"string\"==typeof value?value:null==value?\"\":value+\"\"}function indexOfNaN(array,fromIndex,fromRight){for(var length=array.length,index=fromIndex+(fromRight?0:-1);fromRight?index--:length>++index;){var other=array[index];if(other!==other)return index}return-1}function isObjectLike(value){return!!value&&\"object\"==typeof value}function lodash(){}function arrayCopy(source,array){var index=-1,length=source.length;for(array||(array=Array(length));length>++index;)array[index]=source[index];return array}function arrayEach(array,iteratee){for(var index=-1,length=array.length;length>++index&&iteratee(array[index],index,array)!==!1;);return array}function arrayFilter(array,predicate){for(var index=-1,length=array.length,resIndex=-1,result=[];length>++index;){var value=array[index];predicate(value,index,array)&&(result[++resIndex]=value)}return result}function arrayMap(array,iteratee){for(var index=-1,length=array.length,result=Array(length);length>++index;)result[index]=iteratee(array[index],index,array);return result}function arrayMax(array){for(var index=-1,length=array.length,result=NEGATIVE_INFINITY;length>++index;){var value=array[index];value>result&&(result=value)}return result}function arraySome(array,predicate){for(var index=-1,length=array.length;length>++index;)if(predicate(array[index],index,array))return!0;return!1}function assignWith(object,source,customizer){var props=keys(source);push.apply(props,getSymbols(source));for(var index=-1,length=props.length;length>++index;){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);(result===result?result===value:value!==value)&&(value!==undefined||key in object)||(object[key]=result)}return object}function baseCopy(source,props,object){object||(object={});for(var index=-1,length=props.length;length>++index;){var key=props[index];object[key]=source[key]}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;return\"function\"==type?thisArg===undefined?func:bindCallback(func,thisArg,argCount):null==func?identity:\"object\"==type?baseMatches(func):thisArg===undefined?property(func):baseMatchesProperty(func,thisArg)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer&&(result=object?customizer(value,key,object):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return arrayCopy(value,result)}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag!=objectTag&&tag!=argsTag&&(!isFunc||object))return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{};if(result=initCloneObject(isFunc?{}:value),!isDeep)return baseAssign(result,value)}stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==value)return stackB[length];return stackA.push(value),stackB.push(result),(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)}),result}function baseFilter(collection,predicate){var result=[];return baseEach(collection,function(value,index,collection){predicate(value,index,collection)&&result.push(value)}),result}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseGet(object,path,pathKey){if(null!=object){pathKey!==undefined&&pathKey in toObject(object)&&(path=[pathKey]);for(var index=-1,length=path.length;null!=object&&length>++index;)var result=object=object[path[index]];return result}}function baseIsEqual(value,other,customizer,isLoose,stackA,stackB){if(value===other)return 0!==value||1/value==1/other;var valType=typeof value,othType=typeof other;return\"function\"!=valType&&\"object\"!=valType&&\"function\"!=othType&&\"object\"!=othType||null==value||null==other?value!==value&&other!==other:baseIsEqualDeep(value,other,baseIsEqual,customizer,isLoose,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;objIsArr||(objTag=objToString.call(object),objTag==argsTag?objTag=objectTag:objTag!=objectTag&&(objIsArr=isTypedArray(object))),othIsArr||(othTag=objToString.call(other),othTag==argsTag?othTag=objectTag:othTag!=objectTag&&(othIsArr=isTypedArray(other)));var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!objIsArr&&!objIsObj)return equalByTag(object,other,objTag);if(!isLoose){var valWrapped=objIsObj&&hasOwnProperty.call(object,\"__wrapped__\"),othWrapped=othIsObj&&hasOwnProperty.call(other,\"__wrapped__\");if(valWrapped||othWrapped)return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isLoose,stackA,stackB)}if(!isSameTag)return!1;stackA||(stackA=[]),stackB||(stackB=[]);for(var length=stackA.length;length--;)if(stackA[length]==object)return stackB[length]==other;stackA.push(object),stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isLoose,stackA,stackB);return stackA.pop(),stackB.pop(),result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){for(var index=-1,length=props.length,noCustomizer=!customizer;length>++index;)if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!(props[index]in object))return!1;for(index=-1;length>++index;){var key=props[index],objValue=object[key],srcValue=values[index];if(noCustomizer&&strictCompareFlags[index])var result=objValue!==undefined||key in object;else result=customizer?customizer(objValue,srcValue,key):undefined,result===undefined&&(result=baseIsEqual(srcValue,objValue,customizer,!0));if(!result)return!1}return!0}function baseMatches(source){var props=keys(source),length=props.length;if(!length)return constant(!0);if(1==length){var key=props[0],value=source[key];if(isStrictComparable(value))return function(object){return null==object?!1:object[key]===value&&(value!==undefined||key in toObject(object))}}for(var values=Array(length),strictCompareFlags=Array(length);length--;)value=source[props[length]],values[length]=value,strictCompareFlags[length]=isStrictComparable(value);return function(object){return null!=object&&baseIsMatch(toObject(object),props,values,strictCompareFlags)}}function baseMatchesProperty(path,value){var isArr=isArray(path),isCommon=isKey(path)&&isStrictComparable(value),pathKey=path+\"\";return path=toPath(path),function(object){if(null==object)return!1;var key=pathKey;if(object=toObject(object),!(!isArr&&isCommon||key in object)){if(object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),null==object)return!1;key=last(path),object=toObject(object)}return object[key]===value?value!==undefined||key in object:baseIsEqual(value,object[key],null,!0)}}function baseMerge(object,source,customizer,stackA,stackB){if(!isObject(object))return object;var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));if(!isSrcArr){var props=keys(source);push.apply(props,getSymbols(source))}return arrayEach(props||source,function(srcValue,key){if(props&&(key=srcValue,srcValue=source[key]),isObjectLike(srcValue))stackA||(stackA=[]),stackB||(stackB=[]),baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB);else{var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue),!isSrcArr&&result===undefined||!isCommon&&(result===result?result===value:value!==value)||(object[key]=result)}}),object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){for(var length=stackA.length,srcValue=source[key];length--;)if(stackA[length]==srcValue)return object[key]=stackB[length],undefined;var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=result===undefined;isCommon&&(result=srcValue,isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))?result=isArray(value)?value:getLength(value)?arrayCopy(value):[]:isPlainObject(srcValue)||isArguments(srcValue)?result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}:isCommon=!1),stackA.push(srcValue),stackB.push(result),isCommon?object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB):(result===result?result!==value:value===value)&&(object[key]=result)}function baseProperty(key){return function(object){return null==object?undefined:object[key]}}function basePropertyDeep(path){var pathKey=path+\"\";return path=toPath(path),function(object){return baseGet(object,path,pathKey)}}function baseSlice(array,start,end){var index=-1,length=array.length;start=null==start?0:+start||0,0>start&&(start=-start>length?0:length+start),end=end===undefined||end>length?length:+end||0,0>end&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);length>++index;)result[index]=array[index+start];return result}function baseSome(collection,predicate){var result;return baseEach(collection,function(value,index,collection){return result=predicate(value,index,collection),!result}),!!result}function baseValues(object,props){for(var index=-1,length=props.length,result=Array(length);length>++index;)result[index]=object[props[index]];return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(\"number\"==typeof value&&value===value&&HALF_MAX_ARRAY_LENGTH>=high){for(;high>low;){var mid=low+high>>>1,computed=array[mid];(retHighest?value>=computed:value>computed)?low=mid+1:high=mid}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);for(var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=value===undefined;high>low;){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN)var setLow=isReflexive||retHighest;else setLow=valIsUndef?isReflexive&&(retHighest||computed!==undefined):retHighest?value>=computed:value>computed;setLow?low=mid+1:high=mid}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(\"function\"!=typeof func)return identity;if(thisArg===undefined)return func;switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}function createAssigner(assigner){return restParam(function(object,sources){var index=-1,length=null==object?0:sources.length,customizer=length>2&&sources[length-2],guard=length>2&&sources[2],thisArg=length>1&&sources[length-1];for(\"function\"==typeof customizer?(customizer=bindCallback(customizer,thisArg,5),length-=2):(customizer=\"function\"==typeof thisArg?thisArg:null,length-=customizer?1:0),guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=3>length?null:customizer,length=1);length>++index;){var source=sources[index];source&&assigner(object,source,customizer)}return object})}function createBaseEach(eachFunc,fromRight){return function(collection,iteratee){var length=collection?getLength(collection):0;if(!isLength(length))return eachFunc(collection,iteratee);for(var index=fromRight?length:-1,iterable=toObject(collection);(fromRight?index--:length>++index)&&iteratee(iterable[index],index,iterable)!==!1;);return collection}}function createBaseFor(fromRight){return function(object,iteratee,keysFunc){for(var iterable=toObject(object),props=keysFunc(object),length=props.length,index=fromRight?length:-1;fromRight?index--:length>++index;){var key=props[index];if(iteratee(iterable[key],key,iterable)===!1)break}return object}}function createFindIndex(fromRight){return function(array,predicate,thisArg){return array&&array.length?(predicate=getCallback(predicate,thisArg,3),baseFindIndex(array,predicate,fromRight)):-1}}function createForEach(arrayFunc,eachFunc){return function(collection,iteratee,thisArg){return\"function\"==typeof iteratee&&thisArg===undefined&&isArray(collection)?arrayFunc(collection,iteratee):eachFunc(collection,bindCallback(iteratee,thisArg,3))}}function equalArrays(array,other,equalFunc,customizer,isLoose,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=!0;if(arrLength!=othLength&&!(isLoose&&othLength>arrLength))return!1;for(;result&&arrLength>++index;){var arrValue=array[index],othValue=other[index];if(result=undefined,customizer&&(result=isLoose?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)),result===undefined)if(isLoose)for(var othIndex=othLength;othIndex--&&(othValue=other[othIndex],!(result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB))););else result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isLoose,stackA,stackB)}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:0==object?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==other+\"\"}return!1}function equalObjects(object,other,equalFunc,customizer,isLoose,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isLoose)return!1;for(var skipCtor=isLoose,index=-1;objLength>++index;){var key=objProps[index],result=isLoose?key in other:hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined,customizer&&(result=isLoose?customizer(othValue,objValue,key):customizer(objValue,othValue,key)),result===undefined&&(result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isLoose,stackA,stackB))}if(!result)return!1;skipCtor||(skipCtor=\"constructor\"==key)}if(!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&\"constructor\"in object&&\"constructor\"in other&&!(\"function\"==typeof objCtor&&objCtor instanceof objCtor&&\"function\"==typeof othCtor&&othCtor instanceof othCtor))return!1}return!0}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;return result=result===callback?baseCallback:result,argCount?result(func,thisArg,argCount):result}function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;return result=result===indexOf?baseIndexOf:result,collection?result(collection,target,fromIndex):result}function initCloneArray(array){var length=array.length,result=new array.constructor(length);return length&&\"string\"==typeof array[0]&&hasOwnProperty.call(array,\"index\")&&(result.index=array.index,result.input=array.input),result}function initCloneObject(object){var Ctor=object.constructor;return\"function\"==typeof Ctor&&Ctor instanceof Ctor||(Ctor=Object),new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isIndex(value,length){return value=+value,length=null==length?MAX_SAFE_INTEGER:length,value>-1&&0==value%1&&length>value}function isIterateeCall(value,index,object){if(!isObject(object))return!1;var type=typeof index;if(\"number\"==type)var length=getLength(object),prereq=isLength(length)&&isIndex(index,length);else prereq=\"string\"==type&&index in object;if(prereq){var other=object[index];return value===value?value===other:other!==other}return!1}function isKey(value,object){var type=typeof value;if(\"string\"==type&&reIsPlainProp.test(value)||\"number\"==type)return!0;if(isArray(value))return!1;var result=!reIsDeepProp.test(value);return result||null!=object&&value in toObject(object)}function isLength(value){return\"number\"==typeof value&&value>-1&&0==value%1&&MAX_SAFE_INTEGER>=value}function isStrictComparable(value){return value===value&&(0===value?1/value>0:!isObject(value))}function shimIsPlainObject(value){var Ctor;if(lodash.support,!isObjectLike(value)||objToString.call(value)!=objectTag||!hasOwnProperty.call(value,\"constructor\")&&(Ctor=value.constructor,\"function\"==typeof Ctor&&!(Ctor instanceof Ctor)))return!1;var result;return baseForIn(value,function(subValue,key){result=key}),result===undefined||hasOwnProperty.call(value,result)}function shimKeys(object){for(var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support,allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object)),index=-1,result=[];propsLength>++index;){var key=props[index];(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key))&&result.push(key)}return result}function toObject(value){return isObject(value)?value:Object(value)}function toPath(value){if(isArray(value))return value;var result=[];return baseToString(value).replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,\"$1\"):number||match)}),result}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length)return-1;if(\"number\"==typeof fromIndex)fromIndex=0>fromIndex?nativeMax(length+fromIndex,0):fromIndex;else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex||0)}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function slice(array,start,end){var length=array?array.length:0;return length?(end&&\"number\"!=typeof end&&isIterateeCall(array,start,end)&&(start=0,end=length),baseSlice(array,start,end)):[]}function unzip(array){for(var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);length>++index;)result[index]=arrayMap(array,baseProperty(index));return result}function includes(collection,target,fromIndex,guard){var length=collection?getLength(collection):0;return isLength(length)||(collection=values(collection),length=collection.length),length?(fromIndex=\"number\"!=typeof fromIndex||guard&&isIterateeCall(target,fromIndex,guard)?0:0>fromIndex?nativeMax(length+fromIndex,0):fromIndex||0,\"string\"==typeof collection||!isArray(collection)&&isString(collection)?length>fromIndex&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1):!1}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;return predicate=getCallback(predicate,thisArg,3),func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;return thisArg&&isIterateeCall(collection,predicate,thisArg)&&(predicate=null),(\"function\"!=typeof predicate||thisArg!==undefined)&&(predicate=getCallback(predicate,thisArg,3)),func(collection,predicate)}function restParam(func,start){if(\"function\"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=nativeMax(start===undefined?func.length-1:+start||0,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),rest=Array(length);length>++index;)rest[index]=args[start+index];switch(start){case 0:return func.call(this,rest);case 1:return func.call(this,args[0],rest);case 2:return func.call(this,args[0],args[1],rest)}var otherArgs=Array(start+1);for(index=-1;start>++index;)otherArgs[index]=args[index];return otherArgs[start]=rest,func.apply(this,otherArgs)}}function clone(value,isDeep,customizer,thisArg){return isDeep&&\"boolean\"!=typeof isDeep&&isIterateeCall(value,isDeep,customizer)?isDeep=!1:\"function\"==typeof isDeep&&(thisArg=customizer,customizer=isDeep,isDeep=!1),customizer=\"function\"==typeof customizer&&bindCallback(customizer,thisArg,1),baseClone(value,isDeep,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag}function isEmpty(value){if(null==value)return!0;var length=getLength(value);return isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))?!length:!keys(value).length}function isObject(value){var type=typeof value;return\"function\"==type||!!value&&\"object\"==type}function isNative(value){return null==value?!1:objToString.call(value)==funcTag?reIsNative.test(fnToString.call(value)):isObjectLike(value)&&reIsHostCtor.test(value)}function isNumber(value){return\"number\"==typeof value||isObjectLike(value)&&objToString.call(value)==numberTag}function isString(value){return\"string\"==typeof value||isObjectLike(value)&&objToString.call(value)==stringTag}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[objToString.call(value)]}function toPlainObject(value){return baseCopy(value,keysIn(value))}function has(object,path){if(null==object)return!1;var result=hasOwnProperty.call(object,path);return result||isKey(path)||(path=toPath(path),object=1==path.length?object:baseGet(object,baseSlice(path,0,-1)),path=last(path),result=null!=object&&hasOwnProperty.call(object,path)),result}function keysIn(object){if(null==object)return[];isObject(object)||(object=Object(object));var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;for(var Ctor=object.constructor,index=-1,isProto=\"function\"==typeof Ctor&&Ctor.prototype===object,result=Array(length),skipIndexes=length>0;length>++index;)result[index]=index+\"\";for(var key in object)skipIndexes&&isIndex(key,length)||\"constructor\"==key&&(isProto||!hasOwnProperty.call(object,key))||result.push(key);return result}function values(object){return baseValues(object,keys(object))}function escapeRegExp(string){return string=baseToString(string),string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,\"\\\\$&\"):string}function callback(func,thisArg,guard){return guard&&isIterateeCall(func,thisArg,guard)&&(thisArg=null),baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function property(path){return isKey(path)?baseProperty(path):basePropertyDeep(path)}var undefined,VERSION=\"3.7.0\",FUNC_ERROR_TEXT=\"Expected a function\",argsTag=\"[object Arguments]\",arrayTag=\"[object Array]\",boolTag=\"[object Boolean]\",dateTag=\"[object Date]\",errorTag=\"[object Error]\",funcTag=\"[object Function]\",mapTag=\"[object Map]\",numberTag=\"[object Number]\",objectTag=\"[object Object]\",regexpTag=\"[object RegExp]\",setTag=\"[object Set]\",stringTag=\"[object String]\",weakMapTag=\"[object WeakMap]\",arrayBufferTag=\"[object ArrayBuffer]\",float32Tag=\"[object Float32Array]\",float64Tag=\"[object Float64Array]\",int8Tag=\"[object Int8Array]\",int16Tag=\"[object Int16Array]\",int32Tag=\"[object Int32Array]\",uint8Tag=\"[object Uint8Array]\",uint8ClampedTag=\"[object Uint8ClampedArray]\",uint16Tag=\"[object Uint16Array]\",uint32Tag=\"[object Uint32Array]\",reIsDeepProp=/\\.|\\[(?:[^[\\]]+|([\"'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*?)\\1\\]/,reIsPlainProp=/^\\w*$/,rePropName=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\n\\\\]|\\\\.)*?)\\2)\\]/g,reRegExpChars=/[.*+?^${}()|[\\]\\/\\\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source),reEscapeChar=/\\\\(\\\\)?/g,reFlags=/\\w*$/,reIsHostCtor=/^\\[object .+?Constructor\\]$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=!1;var objectTypes={\"function\":!0,object:!0},freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,freeGlobal=freeExports&&freeModule&&\"object\"==typeof global&&global&&global.Object&&global,freeSelf=objectTypes[typeof self]&&self&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this,arrayProto=Array.prototype,objectProto=Object.prototype,fnToString=Function.prototype.toString,hasOwnProperty=objectProto.hasOwnProperty,objToString=objectProto.toString,reIsNative=RegExp(\"^\"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\"),ArrayBuffer=isNative(ArrayBuffer=root.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,floor=Math.floor,getOwnPropertySymbols=isNative(getOwnPropertySymbols=Object.getOwnPropertySymbols)&&getOwnPropertySymbols,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,preventExtensions=isNative(Object.preventExtensions=Object.preventExtensions)&&preventExtensions,propertyIsEnumerable=objectProto.propertyIsEnumerable,Uint8Array=isNative(Uint8Array=root.Uint8Array)&&Uint8Array,Float64Array=function(){try{var func=isNative(func=root.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}(),nativeAssign=function(){var object={1:0},func=preventExtensions&&isNative(func=Object.assign)&&func;try{func(preventExtensions(object),\"xo\")}catch(e){}return!object[1]&&func}(),nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1,FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0,MAX_SAFE_INTEGER=Math.pow(2,53)-1,support=lodash.support={};(function(x){var Ctor=function(){this.x=x},props=[];Ctor.prototype={valueOf:x,y:x};for(var key in new Ctor)props.push(key);support.funcDecomp=/\\bthis\\b/.test(function(){return this}),support.funcNames=\"string\"==typeof Function.name;try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=!0}})(1,0);var baseAssign=nativeAssign||function(object,source){return null==source?object:baseCopy(source,getSymbols(source),baseCopy(source,keys(source),object))},baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor();bufferSlice||(bufferClone=ArrayBuffer&&Uint8Array?function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}return byteLength!=offset&&(view=new Uint8Array(result,offset),view.set(new Uint8Array(buffer,offset))),result}:constant(null));var getLength=baseProperty(\"length\"),getSymbols=getOwnPropertySymbols?function(object){return getOwnPropertySymbols(toObject(object))}:constant([]),findLastIndex=createFindIndex(!0),zip=restParam(unzip),forEach=createForEach(arrayEach,baseEach),isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag},isFunction=baseIsFunction(/x/)||Uint8Array&&!baseIsFunction(Uint8Array)?function(value){return objToString.call(value)==funcTag}:baseIsFunction,isPlainObject=getPrototypeOf?function(value){if(!value||objToString.call(value)!=objectTag)return!1;var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)}:shimIsPlainObject,assign=createAssigner(function(object,source,customizer){return customizer?assignWith(object,source,customizer):baseAssign(object,source)}),keys=nativeKeys?function(object){if(object)var Ctor=object.constructor,length=object.length;return\"function\"==typeof Ctor&&Ctor.prototype===object||\"function\"!=typeof object&&isLength(length)?shimKeys(object):isObject(object)?nativeKeys(object):[]}:shimKeys,merge=createAssigner(baseMerge);lodash.assign=assign,lodash.callback=callback,lodash.constant=constant,lodash.forEach=forEach,lodash.keys=keys,lodash.keysIn=keysIn,lodash.merge=merge,lodash.property=property,lodash.reject=reject,lodash.restParam=restParam,lodash.slice=slice,lodash.toPlainObject=toPlainObject,lodash.unzip=unzip,lodash.values=values,lodash.zip=zip,lodash.each=forEach,lodash.extend=assign,lodash.iteratee=callback,lodash.clone=clone,lodash.escapeRegExp=escapeRegExp,lodash.findLastIndex=findLastIndex,lodash.has=has,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isEmpty=isEmpty,lodash.isFunction=isFunction,lodash.isNative=isNative,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isPlainObject=isPlainObject,lodash.isString=isString,lodash.isTypedArray=isTypedArray,lodash.last=last,lodash.some=some,lodash.any=some,lodash.contains=includes,lodash.include=includes,lodash.VERSION=VERSION,freeExports&&freeModule?moduleExports?(freeModule.exports=lodash)._=lodash:freeExports._=lodash:root._=lodash\n}).call(this)}).call(this,\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{})},{}],\"/node_modules/jshint/src/jshint.js\":[function(_dereq_,module,exports){var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),vars=_dereq_(\"./vars.js\"),messages=_dereq_(\"./messages.js\"),Lexer=_dereq_(\"./lex.js\").Lexer,reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,style=_dereq_(\"./style.js\"),options=_dereq_(\"./options.js\"),scopeManager=_dereq_(\"./scope-manager.js\"),JSHINT=function(){\"use strict\";function checkOption(name,t){return name=name.trim(),/^[+-]W\\d{3}$/g.test(name)?!0:-1!==options.validNames.indexOf(name)||\"jslint\"===t.type||_.has(options.removed,name)?!0:(error(\"E001\",t,name),!1)}function isString(obj){return\"[object String]\"===Object.prototype.toString.call(obj)}function isIdentifier(tkn,value){return tkn?tkn.identifier&&tkn.value===value?!0:!1:!1}function isReserved(token){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(token.isProperty)return!1}return!0}function supplant(str,data){return str.replace(/\\{([^{}]*)\\}/g,function(a,b){var r=data[b];return\"string\"==typeof r||\"number\"==typeof r?r:a})}function combine(dest,src){Object.keys(src).forEach(function(name){_.has(JSHINT.blacklist,name)||(dest[name]=src[name])})}function processenforceall(){if(state.option.enforceall){for(var enforceopt in options.bool.enforcing)void 0!==state.option[enforceopt]||options.noenforceall[enforceopt]||(state.option[enforceopt]=!0);for(var relaxopt in options.bool.relaxing)void 0===state.option[relaxopt]&&(state.option[relaxopt]=!1)}}function assume(){processenforceall(),state.option.esversion||state.option.moz||(state.option.esversion=state.option.es3?3:state.option.esnext?6:5),state.inES5()&&combine(predefined,vars.ecmaIdentifiers[5]),state.inES6()&&combine(predefined,vars.ecmaIdentifiers[6]),state.option.module&&(state.option.strict===!0&&(state.option.strict=\"global\"),state.inES6()||warning(\"W134\",state.tokens.next,\"module\",6)),state.option.couch&&combine(predefined,vars.couch),state.option.qunit&&combine(predefined,vars.qunit),state.option.rhino&&combine(predefined,vars.rhino),state.option.shelljs&&(combine(predefined,vars.shelljs),combine(predefined,vars.node)),state.option.typed&&combine(predefined,vars.typed),state.option.phantom&&(combine(predefined,vars.phantom),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.prototypejs&&combine(predefined,vars.prototypejs),state.option.node&&(combine(predefined,vars.node),combine(predefined,vars.typed),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.devel&&combine(predefined,vars.devel),state.option.dojo&&combine(predefined,vars.dojo),state.option.browser&&(combine(predefined,vars.browser),combine(predefined,vars.typed)),state.option.browserify&&(combine(predefined,vars.browser),combine(predefined,vars.typed),combine(predefined,vars.browserify),state.option.strict===!0&&(state.option.strict=\"global\")),state.option.nonstandard&&combine(predefined,vars.nonstandard),state.option.jasmine&&combine(predefined,vars.jasmine),state.option.jquery&&combine(predefined,vars.jquery),state.option.mootools&&combine(predefined,vars.mootools),state.option.worker&&combine(predefined,vars.worker),state.option.wsh&&combine(predefined,vars.wsh),state.option.globalstrict&&state.option.strict!==!1&&(state.option.strict=\"global\"),state.option.yui&&combine(predefined,vars.yui),state.option.mocha&&combine(predefined,vars.mocha)}function quit(code,line,chr){var percentage=Math.floor(100*(line/state.lines.length)),message=messages.errors[code].desc;throw{name:\"JSHintError\",line:line,character:chr,message:message+\" (\"+percentage+\"% scanned).\",raw:message,code:code}}function removeIgnoredMessages(){var ignored=state.ignoredLines;_.isEmpty(ignored)||(JSHINT.errors=_.reject(JSHINT.errors,function(err){return ignored[err.line]}))}function warning(code,t,a,b,c,d){var ch,l,w,msg;if(/^W\\d{3}$/.test(code)){if(state.ignored[code])return;msg=messages.warnings[code]}else/E\\d{3}/.test(code)?msg=messages.errors[code]:/I\\d{3}/.test(code)&&(msg=messages.info[code]);return t=t||state.tokens.next||{},\"(end)\"===t.id&&(t=state.tokens.curr),l=t.line||0,ch=t.from||0,w={id:\"(error)\",raw:msg.desc,code:msg.code,evidence:state.lines[l-1]||\"\",line:l,character:ch,scope:JSHINT.scope,a:a,b:b,c:c,d:d},w.reason=supplant(msg.desc,w),JSHINT.errors.push(w),removeIgnoredMessages(),JSHINT.errors.length>=state.option.maxerr&&quit(\"E043\",l,ch),w}function warningAt(m,l,ch,a,b,c,d){return warning(m,{line:l,from:ch},a,b,c,d)}function error(m,t,a,b,c,d){warning(m,t,a,b,c,d)}function errorAt(m,l,ch,a,b,c,d){return error(m,{line:l,from:ch},a,b,c,d)}function addInternalSrc(elem,src){var i;return i={id:\"(internal)\",elem:elem,value:src},JSHINT.internals.push(i),i}function doOption(){var nt=state.tokens.next,body=nt.body.match(/(-\\s+)?[^\\s,:]+(?:\\s*:\\s*(-\\s+)?[^\\s,]+)?/g)||[],predef={};if(\"globals\"===nt.type){body.forEach(function(g,idx){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(\"-\"===key||!key.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}\"-\"===key.charAt(0)?(key=key.slice(1),val=!1,JSHINT.blacklist[key]=key,delete predefined[key]):predef[key]=\"true\"===val}),combine(predefined,predef);for(var key in predef)_.has(predef,key)&&(declared[key]=nt)}\"exported\"===nt.type&&body.forEach(function(e,idx){if(!e.length){if(idx>0&&idx===body.length-1)return;return error(\"E002\",nt),void 0}state.funct[\"(scope)\"].addExported(e)}),\"members\"===nt.type&&(membersOnly=membersOnly||{},body.forEach(function(m){var ch1=m.charAt(0),ch2=m.charAt(m.length-1);ch1!==ch2||'\"'!==ch1&&\"'\"!==ch1||(m=m.substr(1,m.length-2).replace('\\\\\"','\"')),membersOnly[m]=!1}));var numvals=[\"maxstatements\",\"maxparams\",\"maxdepth\",\"maxcomplexity\",\"maxerr\",\"maxlen\",\"indent\"];(\"jshint\"===nt.type||\"jslint\"===nt.type)&&(body.forEach(function(g){g=g.split(\":\");var key=(g[0]||\"\").trim(),val=(g[1]||\"\").trim();if(checkOption(key,nt))if(numvals.indexOf(key)>=0)if(\"false\"!==val){if(val=+val,\"number\"!=typeof val||!isFinite(val)||0>=val||Math.floor(val)!==val)return error(\"E032\",nt,g[1].trim()),void 0;state.option[key]=val}else state.option[key]=\"indent\"===key?4:!1;else{if(\"validthis\"===key)return state.funct[\"(global)\"]?void error(\"E009\"):\"true\"!==val&&\"false\"!==val?void error(\"E002\",nt):(state.option.validthis=\"true\"===val,void 0);if(\"quotmark\"!==key)if(\"shadow\"!==key)if(\"unused\"!==key)if(\"latedef\"!==key)if(\"ignore\"!==key)if(\"strict\"!==key){\"module\"===key&&(hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"module\"));var esversions={es3:3,es5:5,esnext:6};if(!_.has(esversions,key)){if(\"esversion\"===key){switch(val){case\"5\":state.inES5(!0)&&warning(\"I003\");case\"3\":case\"6\":state.option.moz=!1,state.option.esversion=+val;break;case\"2015\":state.option.moz=!1,state.option.esversion=6;break;default:error(\"E002\",nt)}return hasParsedCode(state.funct)||error(\"E055\",state.tokens.next,\"esversion\"),void 0}var match=/^([+-])(W\\d{3})$/g.exec(key);if(match)return state.ignored[match[2]]=\"-\"===match[1],void 0;var tn;return\"true\"===val||\"false\"===val?(\"jslint\"===nt.type?(tn=options.renamed[key]||key,state.option[tn]=\"true\"===val,void 0!==options.inverted[tn]&&(state.option[tn]=!state.option[tn])):state.option[key]=\"true\"===val,\"newcap\"===key&&(state.option[\"(explicitNewcap)\"]=!0),void 0):(error(\"E002\",nt),void 0)}switch(val){case\"true\":state.option.moz=!1,state.option.esversion=esversions[key];break;case\"false\":state.option.moz||(state.option.esversion=5);break;default:error(\"E002\",nt)}}else switch(val){case\"true\":state.option.strict=!0;break;case\"false\":state.option.strict=!1;break;case\"func\":case\"global\":case\"implied\":state.option.strict=val;break;default:error(\"E002\",nt)}else switch(val){case\"line\":state.ignoredLines[nt.line]=!0,removeIgnoredMessages();break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.latedef=!0;break;case\"false\":state.option.latedef=!1;break;case\"nofunc\":state.option.latedef=\"nofunc\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.unused=!0;break;case\"false\":state.option.unused=!1;break;case\"vars\":case\"strict\":state.option.unused=val;break;default:error(\"E002\",nt)}else switch(val){case\"true\":state.option.shadow=!0;break;case\"outer\":state.option.shadow=\"outer\";break;case\"false\":case\"inner\":state.option.shadow=\"inner\";break;default:error(\"E002\",nt)}else switch(val){case\"true\":case\"false\":state.option.quotmark=\"true\"===val;break;case\"double\":case\"single\":state.option.quotmark=val;break;default:error(\"E002\",nt)}}}),assume())}function peek(p){var t,i=p||0,j=lookahead.length;if(j>i)return lookahead[i];for(;i>=j;)t=lookahead[j],t||(t=lookahead[j]=lex.token()),j+=1;return t||\"(end)\"!==state.tokens.next.id?t:state.tokens.next}function peekIgnoreEOL(){var t,i=0;do t=peek(i++);while(\"(endline)\"===t.id);return t}function advance(id,t){switch(state.tokens.curr.id){case\"(number)\":\".\"===state.tokens.next.id&&warning(\"W005\",state.tokens.curr);break;case\"-\":(\"-\"===state.tokens.next.id||\"--\"===state.tokens.next.id)&&warning(\"W006\");break;case\"+\":(\"+\"===state.tokens.next.id||\"++\"===state.tokens.next.id)&&warning(\"W007\")}for(id&&state.tokens.next.id!==id&&(t?\"(end)\"===state.tokens.next.id?error(\"E019\",t,t.id):error(\"E020\",state.tokens.next,id,t.id,t.line,state.tokens.next.value):(\"(identifier)\"!==state.tokens.next.type||state.tokens.next.value!==id)&&warning(\"W116\",state.tokens.next,id,state.tokens.next.value)),state.tokens.prev=state.tokens.curr,state.tokens.curr=state.tokens.next;;){if(state.tokens.next=lookahead.shift()||lex.token(),state.tokens.next||quit(\"E041\",state.tokens.curr.line),\"(end)\"===state.tokens.next.id||\"(error)\"===state.tokens.next.id)return;if(state.tokens.next.check&&state.tokens.next.check(),state.tokens.next.isSpecial)\"falls through\"===state.tokens.next.type?state.tokens.curr.caseFallsThrough=!0:doOption();else if(\"(endline)\"!==state.tokens.next.id)break}}function isInfix(token){return token.infix||!token.identifier&&!token.template&&!!token.led}function isEndOfExpr(){var curr=state.tokens.curr,next=state.tokens.next;return\";\"===next.id||\"}\"===next.id||\":\"===next.id?!0:isInfix(next)===isInfix(curr)||\"yield\"===curr.id&&state.inMoz()?curr.line!==startLine(next):!1}function isBeginOfExpr(prev){return!prev.left&&\"unary\"!==prev.arity}function expression(rbp,initial){var left,isArray=!1,isObject=!1,isLetExpr=!1;state.nameStack.push(),initial||\"let\"!==state.tokens.next.value||\"(\"!==peek(0).value||(state.inMoz()||warning(\"W118\",state.tokens.next,\"let expressions\"),isLetExpr=!0,state.funct[\"(scope)\"].stack(),advance(\"let\"),advance(\"(\"),state.tokens.prev.fud(),advance(\")\")),\"(end)\"===state.tokens.next.id&&error(\"E006\",state.tokens.curr);var isDangerous=state.option.asi&&state.tokens.prev.line!==startLine(state.tokens.curr)&&_.contains([\"]\",\")\"],state.tokens.prev.id)&&_.contains([\"[\",\"(\"],state.tokens.curr.id);if(isDangerous&&warning(\"W014\",state.tokens.curr,state.tokens.curr.id),advance(),initial&&(state.funct[\"(verb)\"]=state.tokens.curr.value,state.tokens.curr.beginsStmt=!0),initial===!0&&state.tokens.curr.fud)left=state.tokens.curr.fud();else for(state.tokens.curr.nud?left=state.tokens.curr.nud():error(\"E030\",state.tokens.curr,state.tokens.curr.id);(state.tokens.next.lbp>rbp||\"(template)\"===state.tokens.next.type)&&!isEndOfExpr();)isArray=\"Array\"===state.tokens.curr.value,isObject=\"Object\"===state.tokens.curr.value,left&&(left.value||left.first&&left.first.value)&&(\"new\"!==left.value||left.first&&left.first.value&&\".\"===left.first.value)&&(isArray=!1,left.value!==state.tokens.curr.value&&(isObject=!1)),advance(),isArray&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W009\",state.tokens.curr),isObject&&\"(\"===state.tokens.curr.id&&\")\"===state.tokens.next.id&&warning(\"W010\",state.tokens.curr),left&&state.tokens.curr.led?left=state.tokens.curr.led(left):error(\"E033\",state.tokens.curr,state.tokens.curr.id);return isLetExpr&&state.funct[\"(scope)\"].unstack(),state.nameStack.pop(),left}function startLine(token){return token.startLine||token.line}function nobreaknonadjacent(left,right){left=left||state.tokens.curr,right=right||state.tokens.next,state.option.laxbreak||left.line===startLine(right)||warning(\"W014\",right,right.value)}function nolinebreak(t){t=t||state.tokens.curr,t.line!==startLine(state.tokens.next)&&warning(\"E022\",t,t.value)}function nobreakcomma(left,right){left.line!==startLine(right)&&(state.option.laxcomma||(comma.first&&(warning(\"I001\"),comma.first=!1),warning(\"W014\",left,right.value)))}function comma(opts){if(opts=opts||{},opts.peek?nobreakcomma(state.tokens.prev,state.tokens.curr):(nobreakcomma(state.tokens.curr,state.tokens.next),advance(\",\")),state.tokens.next.identifier&&(!opts.property||!state.inES5()))switch(state.tokens.next.value){case\"break\":case\"case\":case\"catch\":case\"continue\":case\"default\":case\"do\":case\"else\":case\"finally\":case\"for\":case\"if\":case\"in\":case\"instanceof\":case\"return\":case\"switch\":case\"throw\":case\"try\":case\"var\":case\"let\":case\"while\":case\"with\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}if(\"(punctuator)\"===state.tokens.next.type)switch(state.tokens.next.value){case\"}\":case\"]\":case\",\":if(opts.allowTrailing)return!0;case\")\":return error(\"E024\",state.tokens.next,state.tokens.next.value),!1}return!0}function symbol(s,p){var x=state.syntax[s];return x&&\"object\"==typeof x||(state.syntax[s]=x={id:s,lbp:p,value:s}),x}function delim(s){var x=symbol(s,0);return x.delim=!0,x}function stmt(s,f){var x=delim(s);return x.identifier=x.reserved=!0,x.fud=f,x}function blockstmt(s,f){var x=stmt(s,f);return x.block=!0,x}function reserveName(x){var c=x.id.charAt(0);return(c>=\"a\"&&\"z\">=c||c>=\"A\"&&\"Z\">=c)&&(x.identifier=x.reserved=!0),x}function prefix(s,f){var x=symbol(s,150);return reserveName(x),x.nud=\"function\"==typeof f?f:function(){return this.arity=\"unary\",this.right=expression(150),(\"++\"===this.id||\"--\"===this.id)&&(state.option.plusplus?warning(\"W016\",this,this.id):!this.right||this.right.identifier&&!isReserved(this.right)||\".\"===this.right.id||\"[\"===this.right.id||warning(\"W017\",this),this.right&&this.right.isMetaProperty?error(\"E031\",this):this.right&&this.right.identifier&&state.funct[\"(scope)\"].block.modify(this.right.value,this)),this},x}function type(s,f){var x=delim(s);return x.type=s,x.nud=f,x}function reserve(name,func){var x=type(name,func);return x.identifier=!0,x.reserved=!0,x}function FutureReservedWord(name,meta){var x=type(name,meta&&meta.nud||function(){return this});return meta=meta||{},meta.isFutureReservedWord=!0,x.value=name,x.identifier=!0,x.reserved=!0,x.meta=meta,x}function reservevar(s,v){return reserve(s,function(){return\"function\"==typeof v&&v(this),this})}function infix(s,f,p,w){var x=symbol(s,p);return reserveName(x),x.infix=!0,x.led=function(left){return w||nobreaknonadjacent(state.tokens.prev,state.tokens.curr),\"in\"!==s&&\"instanceof\"!==s||\"!\"!==left.id||warning(\"W018\",left,\"!\"),\"function\"==typeof f?f(left,this):(this.left=left,this.right=expression(p),this)},x}function application(s){var x=symbol(s,42);return x.led=function(left){return nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left,this.right=doFunction({type:\"arrow\",loneArg:left}),this},x}function relation(s,f){var x=symbol(s,100);return x.led=function(left){nobreaknonadjacent(state.tokens.prev,state.tokens.curr),this.left=left;var right=this.right=expression(100);return isIdentifier(left,\"NaN\")||isIdentifier(right,\"NaN\")?warning(\"W019\",this):f&&f.apply(this,[left,right]),left&&right||quit(\"E041\",state.tokens.curr.line),\"!\"===left.id&&warning(\"W018\",left,\"!\"),\"!\"===right.id&&warning(\"W018\",right,\"!\"),this},x}function isPoorRelation(node){return node&&(\"(number)\"===node.type&&0===+node.value||\"(string)\"===node.type&&\"\"===node.value||\"null\"===node.type&&!state.option.eqnull||\"true\"===node.type||\"false\"===node.type||\"undefined\"===node.type)}function isTypoTypeof(left,right,state){var values;return state.option.notypeof?!1:left&&right?(values=state.inES6()?typeofValues.es6:typeofValues.es3,\"(identifier)\"===right.type&&\"typeof\"===right.value&&\"(string)\"===left.type?!_.contains(values,left.value):!1):!1}function isGlobalEval(left,state){var isGlobal=!1;return\"this\"===left.type&&null===state.funct[\"(context)\"]?isGlobal=!0:\"(identifier)\"===left.type&&(state.option.node&&\"global\"===left.value?isGlobal=!0:!state.option.browser||\"window\"!==left.value&&\"document\"!==left.value||(isGlobal=!0)),isGlobal}function findNativePrototype(left){function walkPrototype(obj){return\"object\"==typeof obj?\"prototype\"===obj.right?obj:walkPrototype(obj.left):void 0}function walkNative(obj){for(;!obj.identifier&&\"object\"==typeof obj.left;)obj=obj.left;return obj.identifier&&natives.indexOf(obj.value)>=0?obj.value:void 0}var natives=[\"Array\",\"ArrayBuffer\",\"Boolean\",\"Collator\",\"DataView\",\"Date\",\"DateTimeFormat\",\"Error\",\"EvalError\",\"Float32Array\",\"Float64Array\",\"Function\",\"Infinity\",\"Intl\",\"Int16Array\",\"Int32Array\",\"Int8Array\",\"Iterator\",\"Number\",\"NumberFormat\",\"Object\",\"RangeError\",\"ReferenceError\",\"RegExp\",\"StopIteration\",\"String\",\"SyntaxError\",\"TypeError\",\"Uint16Array\",\"Uint32Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"URIError\"],prototype=walkPrototype(left);return prototype?walkNative(prototype):void 0}function checkLeftSideAssign(left,assignToken,options){var allowDestructuring=options&&options.allowDestructuring;if(assignToken=assignToken||left,state.option.freeze){var nativeObject=findNativePrototype(left);nativeObject&&warning(\"W121\",left,nativeObject)}return left.identifier&&!left.isMetaProperty&&state.funct[\"(scope)\"].block.reassign(left.value,left),\".\"===left.id?((!left.left||\"arguments\"===left.left.value&&!state.isStrict())&&warning(\"E031\",assignToken),state.nameStack.set(state.tokens.prev),!0):\"{\"===left.id||\"[\"===left.id?(allowDestructuring&&state.tokens.curr.left.destructAssign?state.tokens.curr.left.destructAssign.forEach(function(t){t.id&&state.funct[\"(scope)\"].block.modify(t.id,t.token)}):\"{\"!==left.id&&left.left?\"arguments\"!==left.left.value||state.isStrict()||warning(\"E031\",assignToken):warning(\"E031\",assignToken),\"[\"===left.id&&state.nameStack.set(left.right),!0):left.isMetaProperty?(error(\"E031\",assignToken),!0):left.identifier&&!isReserved(left)?(\"exception\"===state.funct[\"(scope)\"].labeltype(left.value)&&warning(\"W022\",left),state.nameStack.set(left),!0):(left===state.syntax[\"function\"]&&warning(\"W023\",state.tokens.curr),!1)}function assignop(s,f,p){var x=infix(s,\"function\"==typeof f?f:function(left,that){return that.left=left,left&&checkLeftSideAssign(left,that,{allowDestructuring:!0})?(that.right=expression(10),that):(error(\"E031\",that),void 0)},p);return x.exps=!0,x.assign=!0,x}function bitwise(s,f,p){var x=symbol(s,p);return reserveName(x),x.led=\"function\"==typeof f?f:function(left){return state.option.bitwise&&warning(\"W016\",this,this.id),this.left=left,this.right=expression(p),this},x}function bitwiseassignop(s){return assignop(s,function(left,that){return state.option.bitwise&&warning(\"W016\",that,that.id),left&&checkLeftSideAssign(left,that)?(that.right=expression(10),that):(error(\"E031\",that),void 0)},20)}function suffix(s){var x=symbol(s,150);return x.led=function(left){return state.option.plusplus?warning(\"W016\",this,this.id):left.identifier&&!isReserved(left)||\".\"===left.id||\"[\"===left.id||warning(\"W017\",this),left.isMetaProperty?error(\"E031\",this):left&&left.identifier&&state.funct[\"(scope)\"].block.modify(left.value,left),this.left=left,this},x}function optionalidentifier(fnparam,prop,preserve){if(state.tokens.next.identifier){preserve||advance();var curr=state.tokens.curr,val=state.tokens.curr.value;return isReserved(curr)?prop&&state.inES5()?val:fnparam&&\"undefined\"===val?val:(warning(\"W024\",state.tokens.curr,state.tokens.curr.id),val):val}}function identifier(fnparam,prop){var i=optionalidentifier(fnparam,prop,!1);if(i)return i;if(\"...\"===state.tokens.next.value){if(state.inES6(!0)||warning(\"W119\",state.tokens.next,\"spread/rest operator\",\"6\"),advance(),checkPunctuator(state.tokens.next,\"...\"))for(warning(\"E024\",state.tokens.next,\"...\");checkPunctuator(state.tokens.next,\"...\");)advance();return state.tokens.next.identifier?identifier(fnparam,prop):(warning(\"E024\",state.tokens.curr,\"...\"),void 0)}error(\"E030\",state.tokens.next,state.tokens.next.value),\";\"!==state.tokens.next.id&&advance()}function reachable(controlToken){var t,i=0;if(\";\"===state.tokens.next.id&&!controlToken.inBracelessBlock)for(;;){do t=peek(i),i+=1;while(\"(end)\"!==t.id&&\"(comment)\"===t.id);if(t.reach)return;if(\"(endline)\"!==t.id){if(\"function\"===t.id){state.option.latedef===!0&&warning(\"W026\",t);break}warning(\"W027\",t,t.value,controlToken.value);break}}}function parseFinalSemicolon(){if(\";\"!==state.tokens.next.id){if(state.tokens.next.isUnclosed)return advance();var sameLine=startLine(state.tokens.next)===state.tokens.curr.line&&\"(end)\"!==state.tokens.next.id,blockEnd=checkPunctuator(state.tokens.next,\"}\");sameLine&&!blockEnd?errorAt(\"E058\",state.tokens.curr.line,state.tokens.curr.character):state.option.asi||(blockEnd&&!state.option.lastsemic||!sameLine)&&warningAt(\"W033\",state.tokens.curr.line,state.tokens.curr.character)}else advance(\";\")}function statement(){var r,i=indent,t=state.tokens.next,hasOwnScope=!1;if(\";\"===t.id)return advance(\";\"),void 0;var res=isReserved(t);if(res&&t.meta&&t.meta.isFutureReservedWord&&\":\"===peek().id&&(warning(\"W024\",t,t.id),res=!1),t.identifier&&!res&&\":\"===peek().id&&(advance(),advance(\":\"),hasOwnScope=!0,state.funct[\"(scope)\"].stack(),state.funct[\"(scope)\"].block.addBreakLabel(t.value,{token:state.tokens.curr}),state.tokens.next.labelled||\"{\"===state.tokens.next.value||warning(\"W028\",state.tokens.next,t.value,state.tokens.next.value),state.tokens.next.label=t.value,t=state.tokens.next),\"{\"===t.id){var iscase=\"case\"===state.funct[\"(verb)\"]&&\":\"===state.tokens.curr.value;return block(!0,!0,!1,!1,iscase),void 0}return r=expression(0,!0),!r||r.identifier&&\"function\"===r.value||\"(punctuator)\"===r.type&&r.left&&r.left.identifier&&\"function\"===r.left.value||state.isStrict()||\"global\"!==state.option.strict||warning(\"E007\"),t.block||(state.option.expr||r&&r.exps?state.option.nonew&&r&&r.left&&\"(\"===r.id&&\"new\"===r.left.id&&warning(\"W031\",t):warning(\"W030\",state.tokens.curr),parseFinalSemicolon()),indent=i,hasOwnScope&&state.funct[\"(scope)\"].unstack(),r}function statements(){for(var p,a=[];!state.tokens.next.reach&&\"(end)\"!==state.tokens.next.id;)\";\"===state.tokens.next.id?(p=peek(),(!p||\"(\"!==p.id&&\"[\"!==p.id)&&warning(\"W032\"),advance(\";\")):a.push(statement());return a}function directives(){for(var i,p,pn;\"(string)\"===state.tokens.next.id;){if(p=peek(0),\"(endline)\"===p.id){i=1;do pn=peek(i++);while(\"(endline)\"===pn.id);if(\";\"===pn.id)p=pn;else{if(\"[\"===pn.value||\".\"===pn.value)break;state.option.asi&&\"(\"!==pn.value||warning(\"W033\",state.tokens.next)}}else{if(\".\"===p.id||\"[\"===p.id)break;\";\"!==p.id&&warning(\"W033\",p)}advance();var directive=state.tokens.curr.value;(state.directive[directive]||\"use strict\"===directive&&\"implied\"===state.option.strict)&&warning(\"W034\",state.tokens.curr,directive),state.directive[directive]=!0,\";\"===p.id&&advance(\";\")}state.isStrict()&&(state.option[\"(explicitNewcap)\"]||(state.option.newcap=!0),state.option.undef=!0)}function block(ordinary,stmt,isfunc,isfatarrow,iscase){var a,m,t,line,d,b=inblock,old_indent=indent;inblock=ordinary,t=state.tokens.next;var metrics=state.funct[\"(metrics)\"];if(metrics.nestedBlockDepth+=1,metrics.verifyMaxNestedBlockDepthPerFunction(),\"{\"===state.tokens.next.id){if(advance(\"{\"),state.funct[\"(scope)\"].stack(),line=state.tokens.curr.line,\"}\"!==state.tokens.next.id){for(indent+=state.option.indent;!ordinary&&state.tokens.next.from>indent;)indent+=state.option.indent;if(isfunc){m={};for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);directives(),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\"))}a=statements(),metrics.statementCount+=a.length,indent-=state.option.indent}advance(\"}\",t),isfunc&&(state.funct[\"(scope)\"].validateParams(),m&&(state.directive=m)),state.funct[\"(scope)\"].unstack(),indent=old_indent}else if(ordinary)state.funct[\"(noblockscopedvar)\"]=\"for\"!==state.tokens.next.id,state.funct[\"(scope)\"].stack(),(!stmt||state.option.curly)&&warning(\"W116\",state.tokens.next,\"{\",state.tokens.next.value),state.tokens.next.inBracelessBlock=!0,indent+=state.option.indent,a=[statement()],indent-=state.option.indent,state.funct[\"(scope)\"].unstack(),delete state.funct[\"(noblockscopedvar)\"];else if(isfunc){if(state.funct[\"(scope)\"].stack(),m={},!stmt||isfatarrow||state.inMoz()||error(\"W118\",state.tokens.curr,\"function closure expressions\"),!stmt)for(d in state.directive)_.has(state.directive,d)&&(m[d]=state.directive[d]);expression(10),state.option.strict&&state.funct[\"(context)\"][\"(global)\"]&&(m[\"use strict\"]||state.isStrict()||warning(\"E007\")),state.funct[\"(scope)\"].unstack()}else error(\"E021\",state.tokens.next,\"{\",state.tokens.next.value);switch(state.funct[\"(verb)\"]){case\"break\":case\"continue\":case\"return\":case\"throw\":if(iscase)break;default:state.funct[\"(verb)\"]=null}return inblock=b,!ordinary||!state.option.noempty||a&&0!==a.length||warning(\"W035\",state.tokens.prev),metrics.nestedBlockDepth-=1,a}function countMember(m){membersOnly&&\"boolean\"!=typeof membersOnly[m]&&warning(\"W036\",state.tokens.curr,m),\"number\"==typeof member[m]?member[m]+=1:member[m]=1}function comprehensiveArrayExpression(){var res={};res.exps=!0,state.funct[\"(comparray)\"].stack();var reversed=!1;return\"for\"!==state.tokens.next.value&&(reversed=!0,state.inMoz()||warning(\"W116\",state.tokens.next,\"for\",state.tokens.next.value),state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"for\"),\"each\"===state.tokens.next.value&&(advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"define\"),res.left=expression(130),_.contains([\"in\",\"of\"],state.tokens.next.value)?advance():error(\"E045\",state.tokens.curr),state.funct[\"(comparray)\"].setState(\"generate\"),expression(10),advance(\")\"),\"if\"===state.tokens.next.value&&(advance(\"if\"),advance(\"(\"),state.funct[\"(comparray)\"].setState(\"filter\"),res.filter=expression(10),advance(\")\")),reversed||(state.funct[\"(comparray)\"].setState(\"use\"),res.right=expression(10)),advance(\"]\"),state.funct[\"(comparray)\"].unstack(),res}function isMethod(){return state.funct[\"(statement)\"]&&\"class\"===state.funct[\"(statement)\"].type||state.funct[\"(context)\"]&&\"class\"===state.funct[\"(context)\"][\"(verb)\"]}function isPropertyName(token){return token.identifier||\"(string)\"===token.id||\"(number)\"===token.id}function propertyName(preserveOrToken){var id,preserve=!0;return\"object\"==typeof preserveOrToken?id=preserveOrToken:(preserve=preserveOrToken,id=optionalidentifier(!1,!0,preserve)),id?\"object\"==typeof id&&(\"(string)\"===id.id||\"(identifier)\"===id.id?id=id.value:\"(number)\"===id.id&&(id=\"\"+id.value)):\"(string)\"===state.tokens.next.id?(id=state.tokens.next.value,preserve||advance()):\"(number)\"===state.tokens.next.id&&(id=\"\"+state.tokens.next.value,preserve||advance()),\"hasOwnProperty\"===id&&warning(\"W001\"),id}function functionparams(options){function addParam(addParamArgs){state.funct[\"(scope)\"].addParam.apply(state.funct[\"(scope)\"],addParamArgs)}var next,ident,t,paramsIds=[],tokens=[],pastDefault=!1,pastRest=!1,arity=0,loneArg=options&&options.loneArg;if(loneArg&&loneArg.identifier===!0)return state.funct[\"(scope)\"].addParam(loneArg.value,loneArg),{arity:1,params:[loneArg.value]};if(next=state.tokens.next,options&&options.parsedOpening||advance(\"(\"),\")\"===state.tokens.next.id)return advance(\")\"),void 0;for(;;){arity++;var currentParams=[];if(_.contains([\"{\",\"[\"],state.tokens.next.id)){tokens=destructuringPattern();for(t in tokens)t=tokens[t],t.id&&(paramsIds.push(t.id),currentParams.push([t.id,t.token]))}else if(checkPunctuator(state.tokens.next,\"...\")&&(pastRest=!0),ident=identifier(!0))paramsIds.push(ident),currentParams.push([ident,state.tokens.curr]);else for(;!checkPunctuators(state.tokens.next,[\",\",\")\"]);)advance();if(pastDefault&&\"=\"!==state.tokens.next.id&&error(\"W138\",state.tokens.current),\"=\"===state.tokens.next.id&&(state.inES6()||warning(\"W119\",state.tokens.next,\"default parameters\",\"6\"),advance(\"=\"),pastDefault=!0,expression(10)),currentParams.forEach(addParam),\",\"!==state.tokens.next.id)return advance(\")\",next),{arity:arity,params:paramsIds};pastRest&&warning(\"W131\",state.tokens.next),comma()}}function functor(name,token,overwrites){var funct={\"(name)\":name,\"(breakage)\":0,\"(loopage)\":0,\"(tokens)\":{},\"(properties)\":{},\"(catch)\":!1,\"(global)\":!1,\"(line)\":null,\"(character)\":null,\"(metrics)\":null,\"(statement)\":null,\"(context)\":null,\"(scope)\":null,\"(comparray)\":null,\"(generator)\":null,\"(arrow)\":null,\"(params)\":null};return token&&_.extend(funct,{\"(line)\":token.line,\"(character)\":token.character,\"(metrics)\":createMetrics(token)}),_.extend(funct,overwrites),funct[\"(context)\"]&&(funct[\"(scope)\"]=funct[\"(context)\"][\"(scope)\"],funct[\"(comparray)\"]=funct[\"(context)\"][\"(comparray)\"]),funct}function isFunctor(token){return\"(scope)\"in token}function hasParsedCode(funct){return funct[\"(global)\"]&&!funct[\"(verb)\"]}function doTemplateLiteral(left){function end(){if(state.tokens.curr.template&&state.tokens.curr.tail&&state.tokens.curr.context===ctx)return!0;var complete=state.tokens.next.template&&state.tokens.next.tail&&state.tokens.next.context===ctx;return complete&&advance(),complete||state.tokens.next.isUnclosed}var ctx=this.context,noSubst=this.noSubst,depth=this.depth;if(!noSubst)for(;!end();)!state.tokens.next.template||state.tokens.next.depth>depth?expression(0):advance();return{id:\"(template)\",type:\"(template)\",tag:left}}function doFunction(options){var f,token,name,statement,classExprBinding,isGenerator,isArrow,ignoreLoopFunc,oldOption=state.option,oldIgnored=state.ignored;options&&(name=options.name,statement=options.statement,classExprBinding=options.classExprBinding,isGenerator=\"generator\"===options.type,isArrow=\"arrow\"===options.type,ignoreLoopFunc=options.ignoreLoopFunc),state.option=Object.create(state.option),state.ignored=Object.create(state.ignored),state.funct=functor(name||state.nameStack.infer(),state.tokens.next,{\"(statement)\":statement,\"(context)\":state.funct,\"(arrow)\":isArrow,\"(generator)\":isGenerator}),f=state.funct,token=state.tokens.curr,token.funct=state.funct,functions.push(state.funct),state.funct[\"(scope)\"].stack(\"functionouter\");var internallyAccessibleName=name||classExprBinding;internallyAccessibleName&&state.funct[\"(scope)\"].block.add(internallyAccessibleName,classExprBinding?\"class\":\"function\",state.tokens.curr,!1),state.funct[\"(scope)\"].stack(\"functionparams\");var paramsInfo=functionparams(options);return paramsInfo?(state.funct[\"(params)\"]=paramsInfo.params,state.funct[\"(metrics)\"].arity=paramsInfo.arity,state.funct[\"(metrics)\"].verifyMaxParametersPerFunction()):state.funct[\"(metrics)\"].arity=0,isArrow&&(state.inES6(!0)||warning(\"W119\",state.tokens.curr,\"arrow function syntax (=>)\",\"6\"),options.loneArg||advance(\"=>\")),block(!1,!0,!0,isArrow),!state.option.noyield&&isGenerator&&\"yielded\"!==state.funct[\"(generator)\"]&&warning(\"W124\",state.tokens.curr),state.funct[\"(metrics)\"].verifyMaxStatementsPerFunction(),state.funct[\"(metrics)\"].verifyMaxComplexityPerFunction(),state.funct[\"(unusedOption)\"]=state.option.unused,state.option=oldOption,state.ignored=oldIgnored,state.funct[\"(last)\"]=state.tokens.curr.line,state.funct[\"(lastcharacter)\"]=state.tokens.curr.character,state.funct[\"(scope)\"].unstack(),state.funct[\"(scope)\"].unstack(),state.funct=state.funct[\"(context)\"],ignoreLoopFunc||state.option.loopfunc||!state.funct[\"(loopage)\"]||f[\"(isCapturing)\"]&&warning(\"W083\",token),f}function createMetrics(functionStartToken){return{statementCount:0,nestedBlockDepth:-1,ComplexityCount:1,arity:0,verifyMaxStatementsPerFunction:function(){state.option.maxstatements&&this.statementCount>state.option.maxstatements&&warning(\"W071\",functionStartToken,this.statementCount)\n},verifyMaxParametersPerFunction:function(){_.isNumber(state.option.maxparams)&&this.arity>state.option.maxparams&&warning(\"W072\",functionStartToken,this.arity)},verifyMaxNestedBlockDepthPerFunction:function(){state.option.maxdepth&&this.nestedBlockDepth>0&&this.nestedBlockDepth===state.option.maxdepth+1&&warning(\"W073\",null,this.nestedBlockDepth)},verifyMaxComplexityPerFunction:function(){var max=state.option.maxcomplexity,cc=this.ComplexityCount;max&&cc>max&&warning(\"W074\",functionStartToken,cc)}}}function increaseComplexityCount(){state.funct[\"(metrics)\"].ComplexityCount+=1}function checkCondAssignment(expr){var id,paren;switch(expr&&(id=expr.id,paren=expr.paren,\",\"===id&&(expr=expr.exprs[expr.exprs.length-1])&&(id=expr.id,paren=paren||expr.paren)),id){case\"=\":case\"+=\":case\"-=\":case\"*=\":case\"%=\":case\"&=\":case\"|=\":case\"^=\":case\"/=\":paren||state.option.boss||warning(\"W084\")}}function checkProperties(props){if(state.inES5())for(var name in props)props[name]&&props[name].setterToken&&!props[name].getterToken&&warning(\"W078\",props[name].setterToken)}function metaProperty(name,c){if(checkPunctuator(state.tokens.next,\".\")){var left=state.tokens.curr.id;advance(\".\");var id=identifier();return state.tokens.curr.isMetaProperty=!0,name!==id?error(\"E057\",state.tokens.prev,left,id):c(),state.tokens.curr}}function destructuringPattern(options){var isAssignment=options&&options.assignment;return state.inES6()||warning(\"W104\",state.tokens.curr,isAssignment?\"destructuring assignment\":\"destructuring binding\",\"6\"),destructuringPatternRecursive(options)}function destructuringPatternRecursive(options){var ids,identifiers=[],openingParsed=options&&options.openingParsed,isAssignment=options&&options.assignment,recursiveOptions=isAssignment?{assignment:isAssignment}:null,firstToken=openingParsed?state.tokens.curr:state.tokens.next,nextInnerDE=function(){var ident;if(checkPunctuators(state.tokens.next,[\"[\",\"{\"])){ids=destructuringPatternRecursive(recursiveOptions);for(var id in ids)id=ids[id],identifiers.push({id:id.id,token:id.token})}else if(checkPunctuator(state.tokens.next,\",\"))identifiers.push({id:null,token:state.tokens.curr});else{if(!checkPunctuator(state.tokens.next,\"(\")){var is_rest=checkPunctuator(state.tokens.next,\"...\");if(isAssignment){var identifierToken=is_rest?peek(0):state.tokens.next;identifierToken.identifier||warning(\"E030\",identifierToken,identifierToken.value);var assignTarget=expression(155);assignTarget&&(checkLeftSideAssign(assignTarget),assignTarget.identifier&&(ident=assignTarget.value))}else ident=identifier();return ident&&identifiers.push({id:ident,token:state.tokens.curr}),is_rest}advance(\"(\"),nextInnerDE(),advance(\")\")}return!1},assignmentProperty=function(){var id;checkPunctuator(state.tokens.next,\"[\")?(advance(\"[\"),expression(10),advance(\"]\"),advance(\":\"),nextInnerDE()):\"(string)\"===state.tokens.next.id||\"(number)\"===state.tokens.next.id?(advance(),advance(\":\"),nextInnerDE()):(id=identifier(),checkPunctuator(state.tokens.next,\":\")?(advance(\":\"),nextInnerDE()):id&&(isAssignment&&checkLeftSideAssign(state.tokens.curr),identifiers.push({id:id,token:state.tokens.curr})))};if(checkPunctuator(firstToken,\"[\")){openingParsed||advance(\"[\"),checkPunctuator(state.tokens.next,\"]\")&&warning(\"W137\",state.tokens.curr);for(var element_after_rest=!1;!checkPunctuator(state.tokens.next,\"]\");)nextInnerDE()&&!element_after_rest&&checkPunctuator(state.tokens.next,\",\")&&(warning(\"W130\",state.tokens.next),element_after_rest=!0),checkPunctuator(state.tokens.next,\"=\")&&(checkPunctuator(state.tokens.prev,\"...\")?advance(\"]\"):advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"]\")||advance(\",\");advance(\"]\")}else if(checkPunctuator(firstToken,\"{\")){for(openingParsed||advance(\"{\"),checkPunctuator(state.tokens.next,\"}\")&&warning(\"W137\",state.tokens.curr);!checkPunctuator(state.tokens.next,\"}\")&&(assignmentProperty(),checkPunctuator(state.tokens.next,\"=\")&&(advance(\"=\"),\"undefined\"===state.tokens.next.id&&warning(\"W080\",state.tokens.prev,state.tokens.prev.value),expression(10)),checkPunctuator(state.tokens.next,\"}\")||(advance(\",\"),!checkPunctuator(state.tokens.next,\"}\"))););advance(\"}\")}return identifiers}function destructuringPatternMatch(tokens,value){var first=value.first;first&&_.zip(tokens,Array.isArray(first)?first:[first]).forEach(function(val){var token=val[0],value=val[1];token&&value?token.first=value:token&&token.first&&!value&&warning(\"W080\",token.first,token.first.value)})}function blockVariableStatement(type,statement,context){var tokens,lone,value,letblock,prefix=context&&context.prefix,inexport=context&&context.inexport,isLet=\"let\"===type,isConst=\"const\"===type;for(state.inES6()||warning(\"W104\",state.tokens.curr,type,\"6\"),isLet&&\"(\"===state.tokens.next.value?(state.inMoz()||warning(\"W118\",state.tokens.next,\"let block\"),advance(\"(\"),state.funct[\"(scope)\"].stack(),letblock=!0):state.funct[\"(noblockscopedvar)\"]&&error(\"E048\",state.tokens.curr,isConst?\"Const\":\"Let\"),statement.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),!prefix&&isConst&&\"=\"!==state.tokens.next.id&&warning(\"E012\",state.tokens.curr,state.tokens.curr.value);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],state.funct[\"(scope)\"].block.isGlobal()&&predefined[t.id]===!1&&warning(\"W079\",t.token,t.id),t.id&&!state.funct[\"(noblockscopedvar)\"]&&(state.funct[\"(scope)\"].addlabel(t.id,{type:type,token:t.token}),names.push(t.token),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.token.value,t.token)));if(\"=\"===state.tokens.next.id&&(advance(\"=\"),prefix||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),!prefix&&\"=\"===peek(0).id&&state.tokens.next.identifier&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),statement.first=statement.first.concat(names),\",\"!==state.tokens.next.id)break;comma()}return letblock&&(advance(\")\"),block(!0,!0),statement.block=!0,state.funct[\"(scope)\"].unstack()),statement}function classdef(isStatement){return state.inES6()||warning(\"W104\",state.tokens.curr,\"class\",\"6\"),isStatement?(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"class\",token:state.tokens.curr})):state.tokens.next.identifier&&\"extends\"!==state.tokens.next.value?(this.name=identifier(),this.namedExpr=!0):this.name=state.nameStack.infer(),classtail(this),this}function classtail(c){var wasInClassBody=state.inClassBody;\"extends\"===state.tokens.next.value&&(advance(\"extends\"),c.heritage=expression(10)),state.inClassBody=!0,advance(\"{\"),c.body=classbody(c),advance(\"}\"),state.inClassBody=wasInClassBody}function classbody(c){for(var name,isStatic,isGenerator,getset,computed,props=Object.create(null),staticProps=Object.create(null),i=0;\"}\"!==state.tokens.next.id;++i)if(name=state.tokens.next,isStatic=!1,isGenerator=!1,getset=null,\";\"!==name.id){if(\"*\"===name.id&&(isGenerator=!0,advance(\"*\"),name=state.tokens.next),\"[\"===name.id)name=computedPropertyName(),computed=!0;else{if(!isPropertyName(name)){warning(\"W052\",state.tokens.next,state.tokens.next.value||state.tokens.next.type),advance();continue}advance(),computed=!1,name.identifier&&\"static\"===name.value&&(checkPunctuator(state.tokens.next,\"*\")&&(isGenerator=!0,advance(\"*\")),(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,isStatic=!0,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())),!name.identifier||\"get\"!==name.value&&\"set\"!==name.value||(isPropertyName(state.tokens.next)||\"[\"===state.tokens.next.id)&&(computed=\"[\"===state.tokens.next.id,getset=name,name=state.tokens.next,\"[\"===state.tokens.next.id?name=computedPropertyName():advance())}if(!checkPunctuator(state.tokens.next,\"(\")){for(error(\"E054\",state.tokens.next,state.tokens.next.value);\"}\"!==state.tokens.next.id&&!checkPunctuator(state.tokens.next,\"(\");)advance();\"(\"!==state.tokens.next.value&&doFunction({statement:c})}if(computed||(getset?saveAccessor(getset.value,isStatic?staticProps:props,name.value,name,!0,isStatic):(\"constructor\"===name.value?state.nameStack.set(c):state.nameStack.set(name),saveProperty(isStatic?staticProps:props,name.value,name,!0,isStatic))),getset&&\"constructor\"===name.value){var propDesc=\"get\"===getset.value?\"class getter method\":\"class setter method\";error(\"E049\",name,propDesc,\"constructor\")}else\"prototype\"===name.value&&error(\"E049\",name,\"class method\",\"prototype\");propertyName(name),doFunction({statement:c,type:isGenerator?\"generator\":null,classExprBinding:c.namedExpr?c.name:null})}else warning(\"W032\"),advance(\";\");checkProperties(props)}function saveProperty(props,name,tkn,isClass,isStatic){var msg=[\"key\",\"class method\",\"static class method\"];msg=msg[(isClass||!1)+(isStatic||!1)],tkn.identifier&&(name=tkn.value),props[name]&&\"__proto__\"!==name?warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name].basic=!0,props[name].basictkn=tkn}function saveAccessor(accessorType,props,name,tkn,isClass,isStatic){var flagName=\"get\"===accessorType?\"getterToken\":\"setterToken\",msg=\"\";isClass?(isStatic&&(msg+=\"static \"),msg+=accessorType+\"ter method\"):msg=\"key\",state.tokens.curr.accessorType=accessorType,state.nameStack.set(tkn),props[name]?(props[name].basic||props[name][flagName])&&\"__proto__\"!==name&&warning(\"W075\",state.tokens.next,msg,name):props[name]=Object.create(null),props[name][flagName]=tkn}function computedPropertyName(){advance(\"[\"),state.inES6()||warning(\"W119\",state.tokens.curr,\"computed property names\",\"6\");var value=expression(10);return advance(\"]\"),value}function checkPunctuators(token,values){return\"(punctuator)\"===token.type?_.contains(values,token.value):!1}function checkPunctuator(token,value){return\"(punctuator)\"===token.type&&token.value===value}function destructuringAssignOrJsonValue(){var block=lookupBlockType();block.notJson?(!state.inES6()&&block.isDestAssign&&warning(\"W104\",state.tokens.curr,\"destructuring assignment\",\"6\"),statements()):(state.option.laxbreak=!0,state.jsonMode=!0,jsonValue())}function jsonValue(){function jsonObject(){var o={},t=state.tokens.next;if(advance(\"{\"),\"}\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E026\",state.tokens.next,t.line);else{if(\"}\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id?error(\"E028\",state.tokens.next):\"(string)\"!==state.tokens.next.id&&warning(\"W095\",state.tokens.next,state.tokens.next.value)}if(o[state.tokens.next.value]===!0?warning(\"W075\",state.tokens.next,\"key\",state.tokens.next.value):\"__proto__\"===state.tokens.next.value&&!state.option.proto||\"__iterator__\"===state.tokens.next.value&&!state.option.iterator?warning(\"W096\",state.tokens.next,state.tokens.next.value):o[state.tokens.next.value]=!0,advance(),advance(\":\"),jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"}\")}function jsonArray(){var t=state.tokens.next;if(advance(\"[\"),\"]\"!==state.tokens.next.id)for(;;){if(\"(end)\"===state.tokens.next.id)error(\"E027\",state.tokens.next,t.line);else{if(\"]\"===state.tokens.next.id){warning(\"W094\",state.tokens.curr);break}\",\"===state.tokens.next.id&&error(\"E028\",state.tokens.next)}if(jsonValue(),\",\"!==state.tokens.next.id)break;advance(\",\")}advance(\"]\")}switch(state.tokens.next.id){case\"{\":jsonObject();break;case\"[\":jsonArray();break;case\"true\":case\"false\":case\"null\":case\"(number)\":case\"(string)\":advance();break;case\"-\":advance(\"-\"),advance(\"(number)\");break;default:error(\"E003\",state.tokens.next)}}var api,declared,functions,inblock,indent,lookahead,lex,member,membersOnly,predefined,stack,urls,bang={\"<\":!0,\"<=\":!0,\"==\":!0,\"===\":!0,\"!==\":!0,\"!=\":!0,\">\":!0,\">=\":!0,\"+\":!0,\"-\":!0,\"*\":!0,\"/\":!0,\"%\":!0},functionicity=[\"closure\",\"exception\",\"global\",\"label\",\"outer\",\"unused\",\"var\"],extraModules=[],emitter=new events.EventEmitter,typeofValues={};typeofValues.legacy=[\"xml\",\"unknown\"],typeofValues.es3=[\"undefined\",\"boolean\",\"number\",\"string\",\"function\",\"object\"],typeofValues.es3=typeofValues.es3.concat(typeofValues.legacy),typeofValues.es6=typeofValues.es3.concat(\"symbol\"),type(\"(number)\",function(){return this}),type(\"(string)\",function(){return this}),state.syntax[\"(identifier)\"]={type:\"(identifier)\",lbp:0,identifier:!0,nud:function(){var v=this.value;return\"=>\"===state.tokens.next.id?this:(state.funct[\"(comparray)\"].check(v)||state.funct[\"(scope)\"].block.use(v,state.tokens.curr),this)},led:function(){error(\"E033\",state.tokens.next,state.tokens.next.value)}};var baseTemplateSyntax={lbp:0,identifier:!1,template:!0};state.syntax[\"(template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template middle)\"]=_.extend({type:\"(template middle)\",middle:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(template tail)\"]=_.extend({type:\"(template tail)\",tail:!0,noSubst:!1},baseTemplateSyntax),state.syntax[\"(no subst template)\"]=_.extend({type:\"(template)\",nud:doTemplateLiteral,led:doTemplateLiteral,noSubst:!0,tail:!0},baseTemplateSyntax),type(\"(regexp)\",function(){return this}),delim(\"(endline)\"),delim(\"(begin)\"),delim(\"(end)\").reach=!0,delim(\"(error)\").reach=!0,delim(\"}\").reach=!0,delim(\")\"),delim(\"]\"),delim('\"').reach=!0,delim(\"'\").reach=!0,delim(\";\"),delim(\":\").reach=!0,delim(\"#\"),reserve(\"else\"),reserve(\"case\").reach=!0,reserve(\"catch\"),reserve(\"default\").reach=!0,reserve(\"finally\"),reservevar(\"arguments\",function(x){state.isStrict()&&state.funct[\"(global)\"]&&warning(\"E008\",x)}),reservevar(\"eval\"),reservevar(\"false\"),reservevar(\"Infinity\"),reservevar(\"null\"),reservevar(\"this\",function(x){state.isStrict()&&!isMethod()&&!state.option.validthis&&(state.funct[\"(statement)\"]&&state.funct[\"(name)\"].charAt(0)>\"Z\"||state.funct[\"(global)\"])&&warning(\"W040\",x)}),reservevar(\"true\"),reservevar(\"undefined\"),assignop(\"=\",\"assign\",20),assignop(\"+=\",\"assignadd\",20),assignop(\"-=\",\"assignsub\",20),assignop(\"*=\",\"assignmult\",20),assignop(\"/=\",\"assigndiv\",20).nud=function(){error(\"E014\")},assignop(\"%=\",\"assignmod\",20),bitwiseassignop(\"&=\"),bitwiseassignop(\"|=\"),bitwiseassignop(\"^=\"),bitwiseassignop(\"<<=\"),bitwiseassignop(\">>=\"),bitwiseassignop(\">>>=\"),infix(\",\",function(left,that){var expr;if(that.exprs=[left],state.option.nocomma&&warning(\"W127\"),!comma({peek:!0}))return that;for(;;){if(!(expr=expression(10)))break;if(that.exprs.push(expr),\",\"!==state.tokens.next.value||!comma())break}return that},10,!0),infix(\"?\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(10),advance(\":\"),that[\"else\"]=expression(10),that},30);var orPrecendence=40;infix(\"||\",function(left,that){return increaseComplexityCount(),that.left=left,that.right=expression(orPrecendence),that},orPrecendence),infix(\"&&\",\"and\",50),bitwise(\"|\",\"bitor\",70),bitwise(\"^\",\"bitxor\",80),bitwise(\"&\",\"bitand\",90),relation(\"==\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));switch(!0){case!eqnull&&state.option.eqeqeq:this.from=this.character,warning(\"W116\",this,\"===\",\"==\");break;case isPoorRelation(left):warning(\"W041\",this,\"===\",left.value);break;case isPoorRelation(right):warning(\"W041\",this,\"===\",right.value);break;case isTypoTypeof(right,left,state):warning(\"W122\",this,right.value);break;case isTypoTypeof(left,right,state):warning(\"W122\",this,left.value)}return this}),relation(\"===\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!=\",function(left,right){var eqnull=state.option.eqnull&&(\"null\"===(left&&left.value)||\"null\"===(right&&right.value));return!eqnull&&state.option.eqeqeq?(this.from=this.character,warning(\"W116\",this,\"!==\",\"!=\")):isPoorRelation(left)?warning(\"W041\",this,\"!==\",left.value):isPoorRelation(right)?warning(\"W041\",this,\"!==\",right.value):isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"!==\",function(left,right){return isTypoTypeof(right,left,state)?warning(\"W122\",this,right.value):isTypoTypeof(left,right,state)&&warning(\"W122\",this,left.value),this}),relation(\"<\"),relation(\">\"),relation(\"<=\"),relation(\">=\"),bitwise(\"<<\",\"shiftleft\",120),bitwise(\">>\",\"shiftright\",120),bitwise(\">>>\",\"shiftrightunsigned\",120),infix(\"in\",\"in\",120),infix(\"instanceof\",\"instanceof\",120),infix(\"+\",function(left,that){var right;return that.left=left,that.right=right=expression(130),left&&right&&\"(string)\"===left.id&&\"(string)\"===right.id?(left.value+=right.value,left.character=right.character,!state.option.scripturl&&reg.javascriptURL.test(left.value)&&warning(\"W050\",left),left):that},130),prefix(\"+\",\"num\"),prefix(\"+++\",function(){return warning(\"W007\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"+++\",function(left){return warning(\"W007\"),this.left=left,this.right=expression(130),this},130),infix(\"-\",\"sub\",130),prefix(\"-\",\"neg\"),prefix(\"---\",function(){return warning(\"W006\"),this.arity=\"unary\",this.right=expression(150),this}),infix(\"---\",function(left){return warning(\"W006\"),this.left=left,this.right=expression(130),this},130),infix(\"*\",\"mult\",140),infix(\"/\",\"div\",140),infix(\"%\",\"mod\",140),suffix(\"++\"),prefix(\"++\",\"preinc\"),state.syntax[\"++\"].exps=!0,suffix(\"--\"),prefix(\"--\",\"predec\"),state.syntax[\"--\"].exps=!0,prefix(\"delete\",function(){var p=expression(10);return p?(\".\"!==p.id&&\"[\"!==p.id&&warning(\"W051\"),this.first=p,p.identifier&&!state.isStrict()&&(p.forgiveUndef=!0),this):this}).exps=!0,prefix(\"~\",function(){return state.option.bitwise&&warning(\"W016\",this,\"~\"),this.arity=\"unary\",this.right=expression(150),this}),prefix(\"...\",function(){return state.inES6(!0)||warning(\"W119\",this,\"spread/rest operator\",\"6\"),state.tokens.next.identifier||\"(string)\"===state.tokens.next.type||checkPunctuators(state.tokens.next,[\"[\",\"(\"])||error(\"E030\",state.tokens.next,state.tokens.next.value),expression(150),this}),prefix(\"!\",function(){return this.arity=\"unary\",this.right=expression(150),this.right||quit(\"E041\",this.line||0),bang[this.right.id]===!0&&warning(\"W018\",this,\"!\"),this}),prefix(\"typeof\",function(){var p=expression(150);return this.first=this.right=p,p||quit(\"E041\",this.line||0,this.character||0),p.identifier&&(p.forgiveUndef=!0),this}),prefix(\"new\",function(){var mp=metaProperty(\"target\",function(){state.inES6(!0)||warning(\"W119\",state.tokens.prev,\"new.target\",\"6\");for(var inFunction,c=state.funct;c&&(inFunction=!c[\"(global)\"],c[\"(arrow)\"]);)c=c[\"(context)\"];inFunction||warning(\"W136\",state.tokens.prev,\"new.target\")});if(mp)return mp;var i,c=expression(155);if(c&&\"function\"!==c.id)if(c.identifier)switch(c[\"new\"]=!0,c.value){case\"Number\":case\"String\":case\"Boolean\":case\"Math\":case\"JSON\":warning(\"W053\",state.tokens.prev,c.value);break;case\"Symbol\":state.inES6()&&warning(\"W053\",state.tokens.prev,c.value);break;case\"Function\":state.option.evil||warning(\"W054\");break;case\"Date\":case\"RegExp\":case\"this\":break;default:\"function\"!==c.id&&(i=c.value.substr(0,1),state.option.newcap&&(\"A\">i||i>\"Z\")&&!state.funct[\"(scope)\"].isPredefined(c.value)&&warning(\"W055\",state.tokens.curr))}else\".\"!==c.id&&\"[\"!==c.id&&\"(\"!==c.id&&warning(\"W056\",state.tokens.curr);else state.option.supernew||warning(\"W057\",this);return\"(\"===state.tokens.next.id||state.option.supernew||warning(\"W058\",state.tokens.curr,state.tokens.curr.value),this.first=this.right=c,this}),state.syntax[\"new\"].exps=!0,prefix(\"void\").exps=!0,infix(\".\",function(left,that){var m=identifier(!1,!0);return\"string\"==typeof m&&countMember(m),that.left=left,that.right=m,m&&\"hasOwnProperty\"===m&&\"=\"===state.tokens.next.value&&warning(\"W001\"),!left||\"arguments\"!==left.value||\"callee\"!==m&&\"caller\"!==m?state.option.evil||!left||\"document\"!==left.value||\"write\"!==m&&\"writeln\"!==m||warning(\"W060\",left):state.option.noarg?warning(\"W059\",left,m):state.isStrict()&&error(\"E008\"),state.option.evil||\"eval\"!==m&&\"execScript\"!==m||isGlobalEval(left,state)&&warning(\"W061\"),that},160,!0),infix(\"(\",function(left,that){state.option.immed&&left&&!left.immed&&\"function\"===left.id&&warning(\"W062\");var n=0,p=[];if(left&&\"(identifier)\"===left.type&&left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)&&-1===\"Array Number String Boolean Date Object Error Symbol\".indexOf(left.value)&&(\"Math\"===left.value?warning(\"W063\",left):state.option.newcap&&warning(\"W064\",left)),\")\"!==state.tokens.next.id)for(;p[p.length]=expression(10),n+=1,\",\"===state.tokens.next.id;)comma();return advance(\")\"),\"object\"==typeof left&&(state.inES5()||\"parseInt\"!==left.value||1!==n||warning(\"W065\",state.tokens.curr),state.option.evil||(\"eval\"===left.value||\"Function\"===left.value||\"execScript\"===left.value?(warning(\"W061\",left),p[0]&&\"(string)\"===[0].id&&addInternalSrc(left,p[0].value)):!p[0]||\"(string)\"!==p[0].id||\"setTimeout\"!==left.value&&\"setInterval\"!==left.value?!p[0]||\"(string)\"!==p[0].id||\".\"!==left.value||\"window\"!==left.left.value||\"setTimeout\"!==left.right&&\"setInterval\"!==left.right||(warning(\"W066\",left),addInternalSrc(left,p[0].value)):(warning(\"W066\",left),addInternalSrc(left,p[0].value))),left.identifier||\".\"===left.id||\"[\"===left.id||\"=>\"===left.id||\"(\"===left.id||\"&&\"===left.id||\"||\"===left.id||\"?\"===left.id||state.inES6()&&left[\"(name)\"]||warning(\"W067\",that)),that.left=left,that},155,!0).exps=!0,prefix(\"(\",function(){var pn1,ret,triggerFnExpr,first,last,pn=state.tokens.next,i=-1,parens=1,opening=state.tokens.curr,preceeding=state.tokens.prev,isNecessary=!state.option.singleGroups;do\"(\"===pn.value?parens+=1:\")\"===pn.value&&(parens-=1),i+=1,pn1=pn,pn=peek(i);while((0!==parens||\")\"!==pn1.value)&&\";\"!==pn.value&&\"(end)\"!==pn.type);if(\"function\"===state.tokens.next.id&&(triggerFnExpr=state.tokens.next.immed=!0),\"=>\"===pn.value)return doFunction({type:\"arrow\",parsedOpening:!0});var exprs=[];if(\")\"!==state.tokens.next.id)for(;exprs.push(expression(10)),\",\"===state.tokens.next.id;)state.option.nocomma&&warning(\"W127\"),comma();return advance(\")\",this),state.option.immed&&exprs[0]&&\"function\"===exprs[0].id&&\"(\"!==state.tokens.next.id&&\".\"!==state.tokens.next.id&&\"[\"!==state.tokens.next.id&&warning(\"W068\",this),exprs.length?(exprs.length>1?(ret=Object.create(state.syntax[\",\"]),ret.exprs=exprs,first=exprs[0],last=exprs[exprs.length-1],isNecessary||(isNecessary=preceeding.assign||preceeding.delim)):(ret=first=last=exprs[0],isNecessary||(isNecessary=opening.beginsStmt&&(\"{\"===ret.id||triggerFnExpr||isFunctor(ret))||triggerFnExpr&&(!isEndOfExpr()||\"}\"!==state.tokens.prev.id)||isFunctor(ret)&&!isEndOfExpr()||\"{\"===ret.id&&\"=>\"===preceeding.id||\"(number)\"===ret.type&&checkPunctuator(pn,\".\")&&/^\\d+$/.test(ret.value))),ret&&(!isNecessary&&(first.left||first.right||ret.exprs)&&(isNecessary=!isBeginOfExpr(preceeding)&&first.lbp<=preceeding.lbp||!isEndOfExpr()&&last.lbp<state.tokens.next.lbp),isNecessary||warning(\"W126\",opening),ret.paren=!0),ret):void 0}),application(\"=>\"),infix(\"[\",function(left,that){var s,e=expression(10);return e&&\"(string)\"===e.type&&(state.option.evil||\"eval\"!==e.value&&\"execScript\"!==e.value||isGlobalEval(left,state)&&warning(\"W061\"),countMember(e.value),!state.option.sub&&reg.identifier.test(e.value)&&(s=state.syntax[e.value],s&&isReserved(s)||warning(\"W069\",state.tokens.prev,e.value))),advance(\"]\",that),e&&\"hasOwnProperty\"===e.value&&\"=\"===state.tokens.next.value&&warning(\"W001\"),that.left=left,that.right=e,that},160,!0),prefix(\"[\",function(){var blocktype=lookupBlockType();if(blocktype.isCompArray)return state.option.esnext||state.inMoz()||warning(\"W118\",state.tokens.curr,\"array comprehension\"),comprehensiveArrayExpression();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;var b=state.tokens.curr.line!==startLine(state.tokens.next);for(this.first=[],b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));\"(end)\"!==state.tokens.next.id;){for(;\",\"===state.tokens.next.id;){if(!state.option.elision){if(state.inES5()){warning(\"W128\");do advance(\",\");while(\",\"===state.tokens.next.id);continue}warning(\"W070\")}advance(\",\")}if(\"]\"===state.tokens.next.id)break;if(this.first.push(expression(10)),\",\"!==state.tokens.next.id)break;if(comma({allowTrailing:!0}),\"]\"===state.tokens.next.id&&!state.inES5()){warning(\"W070\",state.tokens.curr);break}}return b&&(indent-=state.option.indent),advance(\"]\",this),this}),function(x){x.nud=function(){var b,f,i,p,t,nextVal,isGeneratorMethod=!1,props=Object.create(null);b=state.tokens.curr.line!==startLine(state.tokens.next),b&&(indent+=state.option.indent,state.tokens.next.from===indent+state.option.indent&&(indent+=state.option.indent));var blocktype=lookupBlockType();if(blocktype.isDestAssign)return this.destructAssign=destructuringPattern({openingParsed:!0,assignment:!0}),this;for(;\"}\"!==state.tokens.next.id;){if(nextVal=state.tokens.next.value,!state.tokens.next.identifier||\",\"!==peekIgnoreEOL().id&&\"}\"!==peekIgnoreEOL().id)if(\":\"===peek().id||\"get\"!==nextVal&&\"set\"!==nextVal){if(\"*\"===state.tokens.next.value&&\"(punctuator)\"===state.tokens.next.type?(state.inES6()||warning(\"W104\",state.tokens.next,\"generator functions\",\"6\"),advance(\"*\"),isGeneratorMethod=!0):isGeneratorMethod=!1,\"[\"===state.tokens.next.id)i=computedPropertyName(),state.nameStack.set(i);else if(state.nameStack.set(state.tokens.next),i=propertyName(),saveProperty(props,i,state.tokens.next),\"string\"!=typeof i)break;\"(\"===state.tokens.next.value?(state.inES6()||warning(\"W104\",state.tokens.curr,\"concise methods\",\"6\"),doFunction({type:isGeneratorMethod?\"generator\":null})):(advance(\":\"),expression(10))}else advance(nextVal),state.inES5()||error(\"E034\"),i=propertyName(),i||state.inES6()||error(\"E035\"),i&&saveAccessor(nextVal,props,i,state.tokens.curr),t=state.tokens.next,f=doFunction(),p=f[\"(params)\"],\"get\"===nextVal&&i&&p?warning(\"W076\",t,p[0],i):\"set\"!==nextVal||!i||p&&1===p.length||warning(\"W077\",t,i);else state.inES6()||warning(\"W104\",state.tokens.next,\"object short notation\",\"6\"),i=propertyName(!0),saveProperty(props,i,state.tokens.next),expression(10);if(countMember(i),\",\"!==state.tokens.next.id)break;comma({allowTrailing:!0,property:!0}),\",\"===state.tokens.next.id?warning(\"W070\",state.tokens.curr):\"}\"!==state.tokens.next.id||state.inES5()||warning(\"W070\",state.tokens.curr)}return b&&(indent-=state.option.indent),advance(\"}\",this),checkProperties(props),this},x.fud=function(){error(\"E036\",state.tokens.curr)}}(delim(\"{\"));var conststatement=stmt(\"const\",function(context){return blockVariableStatement(\"const\",this,context)});conststatement.exps=!0;var letstatement=stmt(\"let\",function(context){return blockVariableStatement(\"let\",this,context)});letstatement.exps=!0;var varstatement=stmt(\"var\",function(context){var tokens,lone,value,prefix=context&&context.prefix,inexport=context&&context.inexport,implied=context&&context.implied,report=!(context&&context.ignore);for(this.first=[];;){var names=[];_.contains([\"{\",\"[\"],state.tokens.next.value)?(tokens=destructuringPattern(),lone=!1):(tokens=[{id:identifier(),token:state.tokens.curr}],lone=!0),prefix&&implied||!report||!state.option.varstmt||warning(\"W132\",this),this.first=this.first.concat(names);for(var t in tokens)tokens.hasOwnProperty(t)&&(t=tokens[t],!implied&&state.funct[\"(global)\"]&&(predefined[t.id]===!1?warning(\"W079\",t.token,t.id):state.option.futurehostile===!1&&(!state.inES5()&&vars.ecmaIdentifiers[5][t.id]===!1||!state.inES6()&&vars.ecmaIdentifiers[6][t.id]===!1)&&warning(\"W129\",t.token,t.id)),t.id&&(\"for\"===implied?(state.funct[\"(scope)\"].has(t.id)||report&&warning(\"W088\",t.token,t.id),state.funct[\"(scope)\"].block.use(t.id,t.token)):(state.funct[\"(scope)\"].addlabel(t.id,{type:\"var\",token:t.token}),lone&&inexport&&state.funct[\"(scope)\"].setExported(t.id,t.token)),names.push(t.token)));if(\"=\"===state.tokens.next.id&&(state.nameStack.set(state.tokens.curr),advance(\"=\"),prefix||!report||state.funct[\"(loopage)\"]||\"undefined\"!==state.tokens.next.id||warning(\"W080\",state.tokens.prev,state.tokens.prev.value),\"=\"===peek(0).id&&state.tokens.next.identifier&&(!prefix&&report&&!state.funct[\"(params)\"]||-1===state.funct[\"(params)\"].indexOf(state.tokens.next.value))&&warning(\"W120\",state.tokens.next,state.tokens.next.value),value=expression(prefix?120:10),lone?tokens[0].first=value:destructuringPatternMatch(names,value)),\",\"!==state.tokens.next.id)break;comma()}return this});varstatement.exps=!0,blockstmt(\"class\",function(){return classdef.call(this,!0)}),blockstmt(\"function\",function(context){var inexport=context&&context.inexport,generator=!1;\"*\"===state.tokens.next.value&&(advance(\"*\"),state.inES6({strict:!0})?generator=!0:warning(\"W119\",state.tokens.curr,\"function*\",\"6\")),inblock&&warning(\"W082\",state.tokens.curr);var i=optionalidentifier();return state.funct[\"(scope)\"].addlabel(i,{type:\"function\",token:state.tokens.curr}),void 0===i?warning(\"W025\"):inexport&&state.funct[\"(scope)\"].setExported(i,state.tokens.prev),doFunction({name:i,statement:this,type:generator?\"generator\":null,ignoreLoopFunc:inblock}),\"(\"===state.tokens.next.id&&state.tokens.next.line===state.tokens.curr.line&&error(\"E039\"),this}),prefix(\"function\",function(){var generator=!1;\"*\"===state.tokens.next.value&&(state.inES6()||warning(\"W119\",state.tokens.curr,\"function*\",\"6\"),advance(\"*\"),generator=!0);var i=optionalidentifier();return doFunction({name:i,type:generator?\"generator\":null}),this}),blockstmt(\"if\",function(){var t=state.tokens.next;increaseComplexityCount(),state.condition=!0,advance(\"(\");var expr=expression(0);checkCondAssignment(expr);var forinifcheck=null;state.option.forin&&state.forinifcheckneeded&&(state.forinifcheckneeded=!1,forinifcheck=state.forinifchecks[state.forinifchecks.length-1],forinifcheck.type=\"(punctuator)\"===expr.type&&\"!\"===expr.value?\"(negative)\":\"(positive)\"),advance(\")\",t),state.condition=!1;var s=block(!0,!0);return forinifcheck&&\"(negative)\"===forinifcheck.type&&s&&s[0]&&\"(identifier)\"===s[0].type&&\"continue\"===s[0].value&&(forinifcheck.type=\"(negative-with-continue)\"),\"else\"===state.tokens.next.id&&(advance(\"else\"),\"if\"===state.tokens.next.id||\"switch\"===state.tokens.next.id?statement():block(!0,!0)),this}),blockstmt(\"try\",function(){function doCatch(){if(advance(\"catch\"),advance(\"(\"),state.funct[\"(scope)\"].stack(\"catchparams\"),checkPunctuators(state.tokens.next,[\"[\",\"{\"])){var tokens=destructuringPattern();_.each(tokens,function(token){token.id&&state.funct[\"(scope)\"].addParam(token.id,token,\"exception\")})}else\"(identifier)\"!==state.tokens.next.type?warning(\"E030\",state.tokens.next,state.tokens.next.value):state.funct[\"(scope)\"].addParam(identifier(),state.tokens.curr,\"exception\");\"if\"===state.tokens.next.value&&(state.inMoz()||warning(\"W118\",state.tokens.curr,\"catch filter\"),advance(\"if\"),expression(0)),advance(\")\"),block(!1),state.funct[\"(scope)\"].unstack()}var b;for(block(!0);\"catch\"===state.tokens.next.id;)increaseComplexityCount(),b&&!state.inMoz()&&warning(\"W118\",state.tokens.next,\"multiple catch blocks\"),doCatch(),b=!0;return\"finally\"===state.tokens.next.id?(advance(\"finally\"),block(!0),void 0):(b||error(\"E021\",state.tokens.next,\"catch\",state.tokens.next.value),this)}),blockstmt(\"while\",function(){var t=state.tokens.next;return state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this}).labelled=!0,blockstmt(\"with\",function(){var t=state.tokens.next;return state.isStrict()?error(\"E010\",state.tokens.curr):state.option.withstmt||warning(\"W085\",state.tokens.curr),advance(\"(\"),expression(0),advance(\")\",t),block(!0,!0),this}),blockstmt(\"switch\",function(){var t=state.tokens.next,g=!1,noindent=!1;\nfor(state.funct[\"(breakage)\"]+=1,advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),t=state.tokens.next,advance(\"{\"),state.tokens.next.from===indent&&(noindent=!0),noindent||(indent+=state.option.indent),this.cases=[];;)switch(state.tokens.next.id){case\"case\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"case\":case\"continue\":case\"return\":case\"switch\":case\"throw\":break;default:state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"case\")}advance(\"case\"),this.cases.push(expression(0)),increaseComplexityCount(),g=!0,advance(\":\"),state.funct[\"(verb)\"]=\"case\";break;case\"default\":switch(state.funct[\"(verb)\"]){case\"yield\":case\"break\":case\"continue\":case\"return\":case\"throw\":break;default:this.cases.length&&(state.tokens.curr.caseFallsThrough||warning(\"W086\",state.tokens.curr,\"default\"))}advance(\"default\"),g=!0,advance(\":\");break;case\"}\":return noindent||(indent-=state.option.indent),advance(\"}\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(verb)\"]=void 0,void 0;case\"(end)\":return error(\"E023\",state.tokens.next,\"}\"),void 0;default:if(indent+=state.option.indent,g)switch(state.tokens.curr.id){case\",\":return error(\"E040\"),void 0;case\":\":g=!1,statements();break;default:return error(\"E025\",state.tokens.curr),void 0}else{if(\":\"!==state.tokens.curr.id)return error(\"E021\",state.tokens.next,\"case\",state.tokens.next.value),void 0;advance(\":\"),error(\"E024\",state.tokens.curr,\":\"),statements()}indent-=state.option.indent}return this}).labelled=!0,stmt(\"debugger\",function(){return state.option.debug||warning(\"W087\",this),this}).exps=!0,function(){var x=stmt(\"do\",function(){state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,increaseComplexityCount(),this.first=block(!0,!0),advance(\"while\");var t=state.tokens.next;return advance(\"(\"),checkCondAssignment(expression(0)),advance(\")\",t),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1,this});x.labelled=!0,x.exps=!0}(),blockstmt(\"for\",function(){var s,t=state.tokens.next,letscope=!1,foreachtok=null;\"each\"===t.value&&(foreachtok=t,advance(\"each\"),state.inMoz()||warning(\"W118\",state.tokens.curr,\"for each\")),increaseComplexityCount(),advance(\"(\");var nextop,comma,initializer,i=0,inof=[\"in\",\"of\"],level=0;checkPunctuators(state.tokens.next,[\"{\",\"[\"])&&++level;do{if(nextop=peek(i),++i,checkPunctuators(nextop,[\"{\",\"[\"])?++level:checkPunctuators(nextop,[\"}\",\"]\"])&&--level,0>level)break;0===level&&(!comma&&checkPunctuator(nextop,\",\")?comma=nextop:!initializer&&checkPunctuator(nextop,\"=\")&&(initializer=nextop))}while(level>0||!_.contains(inof,nextop.value)&&\";\"!==nextop.value&&\"(end)\"!==nextop.type);if(_.contains(inof,nextop.value)){state.inES6()||\"of\"!==nextop.value||warning(\"W104\",nextop,\"for of\",\"6\");var ok=!(initializer||comma);if(initializer&&error(\"W133\",comma,nextop.value,\"initializer is forbidden\"),comma&&error(\"W133\",comma,nextop.value,\"more than one ForBinding\"),\"var\"===state.tokens.next.id?(advance(\"var\"),state.tokens.curr.fud({prefix:!0})):\"let\"===state.tokens.next.id||\"const\"===state.tokens.next.id?(advance(state.tokens.next.id),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud({prefix:!0})):Object.create(varstatement).fud({prefix:!0,implied:\"for\",ignore:!ok}),advance(nextop.value),expression(20),advance(\")\",t),\"in\"===nextop.value&&state.option.forin&&(state.forinifcheckneeded=!0,void 0===state.forinifchecks&&(state.forinifchecks=[]),state.forinifchecks.push({type:\"(none)\"})),state.funct[\"(breakage)\"]+=1,state.funct[\"(loopage)\"]+=1,s=block(!0,!0),\"in\"===nextop.value&&state.option.forin){if(state.forinifchecks&&state.forinifchecks.length>0){var check=state.forinifchecks.pop();(s&&s.length>0&&(\"object\"!=typeof s[0]||\"if\"!==s[0].value)||\"(positive)\"===check.type&&s.length>1||\"(negative)\"===check.type)&&warning(\"W089\",this)}state.forinifcheckneeded=!1}state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}else{if(foreachtok&&error(\"E045\",foreachtok),\";\"!==state.tokens.next.id)if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud();else if(\"let\"===state.tokens.next.id)advance(\"let\"),letscope=!0,state.funct[\"(scope)\"].stack(),state.tokens.curr.fud();else for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();if(nolinebreak(state.tokens.curr),advance(\";\"),state.funct[\"(loopage)\"]+=1,\";\"!==state.tokens.next.id&&checkCondAssignment(expression(0)),nolinebreak(state.tokens.curr),advance(\";\"),\";\"===state.tokens.next.id&&error(\"E021\",state.tokens.next,\")\",\";\"),\")\"!==state.tokens.next.id)for(;expression(0,\"for\"),\",\"===state.tokens.next.id;)comma();advance(\")\",t),state.funct[\"(breakage)\"]+=1,block(!0,!0),state.funct[\"(breakage)\"]-=1,state.funct[\"(loopage)\"]-=1}return letscope&&state.funct[\"(scope)\"].unstack(),this}).labelled=!0,stmt(\"break\",function(){var v=state.tokens.next.value;return state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line!==startLine(state.tokens.next)?0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value):(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"continue\",function(){var v=state.tokens.next.value;return 0===state.funct[\"(breakage)\"]&&warning(\"W052\",state.tokens.next,this.value),state.funct[\"(loopage)\"]||warning(\"W052\",state.tokens.next,this.value),state.option.asi||nolinebreak(this),\";\"===state.tokens.next.id||state.tokens.next.reach||state.tokens.curr.line===startLine(state.tokens.next)&&(state.funct[\"(scope)\"].funct.hasBreakLabel(v)||warning(\"W090\",state.tokens.next,v),this.first=state.tokens.next,advance()),reachable(this),this}).exps=!0,stmt(\"return\",function(){return this.line===startLine(state.tokens.next)?\";\"===state.tokens.next.id||state.tokens.next.reach||(this.first=expression(0),!this.first||\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)):\"(punctuator)\"===state.tokens.next.type&&[\"[\",\"{\",\"+\",\"-\"].indexOf(state.tokens.next.value)>-1&&nolinebreak(this),reachable(this),this}).exps=!0,function(x){x.exps=!0,x.lbp=25}(prefix(\"yield\",function(){var prev=state.tokens.prev;state.inES6(!0)&&!state.funct[\"(generator)\"]?\"(catch)\"===state.funct[\"(name)\"]&&state.funct[\"(context)\"][\"(generator)\"]||error(\"E046\",state.tokens.curr,\"yield\"):state.inES6()||warning(\"W104\",state.tokens.curr,\"yield\",\"6\"),state.funct[\"(generator)\"]=\"yielded\";var delegatingYield=!1;return\"*\"===state.tokens.next.value&&(delegatingYield=!0,advance(\"*\")),this.line!==startLine(state.tokens.next)&&state.inMoz()?state.option.asi||nolinebreak(this):((delegatingYield||\";\"!==state.tokens.next.id&&!state.option.asi&&!state.tokens.next.reach&&state.tokens.next.nud)&&(nobreaknonadjacent(state.tokens.curr,state.tokens.next),this.first=expression(10),\"(punctuator)\"!==this.first.type||\"=\"!==this.first.value||this.first.paren||state.option.boss||warningAt(\"W093\",this.first.line,this.first.character)),state.inMoz()&&\")\"!==state.tokens.next.id&&(prev.lbp>30||!prev.assign&&!isEndOfExpr()||\"yield\"===prev.id)&&error(\"E050\",this)),this})),stmt(\"throw\",function(){return nolinebreak(this),this.first=expression(20),reachable(this),this}).exps=!0,stmt(\"import\",function(){if(state.inES6()||warning(\"W119\",state.tokens.curr,\"import\",\"6\"),\"(string)\"===state.tokens.next.type)return advance(\"(string)\"),this;if(state.tokens.next.identifier){if(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value)return advance(\"from\"),advance(\"(string)\"),this;advance(\",\")}if(\"*\"===state.tokens.next.id)advance(\"*\"),advance(\"as\"),state.tokens.next.identifier&&(this.name=identifier(),state.funct[\"(scope)\"].addlabel(this.name,{type:\"const\",token:state.tokens.curr}));else for(advance(\"{\");;){if(\"}\"===state.tokens.next.value){advance(\"}\");break}var importName;if(\"default\"===state.tokens.next.type?(importName=\"default\",advance(\"default\")):importName=identifier(),\"as\"===state.tokens.next.value&&(advance(\"as\"),importName=identifier()),state.funct[\"(scope)\"].addlabel(importName,{type:\"const\",token:state.tokens.curr}),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return advance(\"from\"),advance(\"(string)\"),this}).exps=!0,stmt(\"export\",function(){var token,identifier,ok=!0;if(state.inES6()||(warning(\"W119\",state.tokens.curr,\"export\",\"6\"),ok=!1),state.funct[\"(scope)\"].block.isGlobal()||(error(\"E053\",state.tokens.curr),ok=!1),\"*\"===state.tokens.next.value)return advance(\"*\"),advance(\"from\"),advance(\"(string)\"),this;if(\"default\"===state.tokens.next.type){state.nameStack.set(state.tokens.next),advance(\"default\");var exportType=state.tokens.next.id;return(\"function\"===exportType||\"class\"===exportType)&&(this.block=!0),token=peek(),expression(10),identifier=token.value,this.block&&(state.funct[\"(scope)\"].addlabel(identifier,{type:exportType,token:token}),state.funct[\"(scope)\"].setExported(identifier,token)),this}if(\"{\"===state.tokens.next.value){advance(\"{\");for(var exportedTokens=[];;){if(state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance(),exportedTokens.push(state.tokens.curr),\"as\"===state.tokens.next.value&&(advance(\"as\"),state.tokens.next.identifier||error(\"E030\",state.tokens.next,state.tokens.next.value),advance()),\",\"!==state.tokens.next.value){if(\"}\"===state.tokens.next.value){advance(\"}\");break}error(\"E024\",state.tokens.next,state.tokens.next.value);break}advance(\",\")}return\"from\"===state.tokens.next.value?(advance(\"from\"),advance(\"(string)\")):ok&&exportedTokens.forEach(function(token){state.funct[\"(scope)\"].setExported(token.value,token)}),this}if(\"var\"===state.tokens.next.id)advance(\"var\"),state.tokens.curr.fud({inexport:!0});else if(\"let\"===state.tokens.next.id)advance(\"let\"),state.tokens.curr.fud({inexport:!0});else if(\"const\"===state.tokens.next.id)advance(\"const\"),state.tokens.curr.fud({inexport:!0});else if(\"function\"===state.tokens.next.id)this.block=!0,advance(\"function\"),state.syntax[\"function\"].fud({inexport:!0});else if(\"class\"===state.tokens.next.id){this.block=!0,advance(\"class\");var classNameToken=state.tokens.next;state.syntax[\"class\"].fud(),state.funct[\"(scope)\"].setExported(classNameToken.value,classNameToken)}else error(\"E024\",state.tokens.next,state.tokens.next.value);return this}).exps=!0,FutureReservedWord(\"abstract\"),FutureReservedWord(\"boolean\"),FutureReservedWord(\"byte\"),FutureReservedWord(\"char\"),FutureReservedWord(\"class\",{es5:!0,nud:classdef}),FutureReservedWord(\"double\"),FutureReservedWord(\"enum\",{es5:!0}),FutureReservedWord(\"export\",{es5:!0}),FutureReservedWord(\"extends\",{es5:!0}),FutureReservedWord(\"final\"),FutureReservedWord(\"float\"),FutureReservedWord(\"goto\"),FutureReservedWord(\"implements\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"import\",{es5:!0}),FutureReservedWord(\"int\"),FutureReservedWord(\"interface\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"long\"),FutureReservedWord(\"native\"),FutureReservedWord(\"package\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"private\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"protected\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"public\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"short\"),FutureReservedWord(\"static\",{es5:!0,strictOnly:!0}),FutureReservedWord(\"super\",{es5:!0}),FutureReservedWord(\"synchronized\"),FutureReservedWord(\"transient\"),FutureReservedWord(\"volatile\");var lookupBlockType=function(){var pn,pn1,prev,i=-1,bracketStack=0,ret={};checkPunctuators(state.tokens.curr,[\"[\",\"{\"])&&(bracketStack+=1);do{if(prev=-1===i?state.tokens.curr:pn,pn=-1===i?state.tokens.next:peek(i),pn1=peek(i+1),i+=1,checkPunctuators(pn,[\"[\",\"{\"])?bracketStack+=1:checkPunctuators(pn,[\"]\",\"}\"])&&(bracketStack-=1),1===bracketStack&&pn.identifier&&\"for\"===pn.value&&!checkPunctuator(prev,\".\")){ret.isCompArray=!0,ret.notJson=!0;break}if(0===bracketStack&&checkPunctuators(pn,[\"}\",\"]\"])){if(\"=\"===pn1.value){ret.isDestAssign=!0,ret.notJson=!0;break}if(\".\"===pn1.value){ret.notJson=!0;break}}checkPunctuator(pn,\";\")&&(ret.isBlock=!0,ret.notJson=!0)}while(bracketStack>0&&\"(end)\"!==pn.id);return ret},arrayComprehension=function(){function declare(v){var l=_current.variables.filter(function(elt){return elt.value===v?(elt.undef=!1,v):void 0}).length;return 0!==l}function use(v){var l=_current.variables.filter(function(elt){return elt.value!==v||elt.undef?void 0:(elt.unused===!0&&(elt.unused=!1),v)}).length;return 0===l}var _current,CompArray=function(){this.mode=\"use\",this.variables=[]},_carrays=[];return{stack:function(){_current=new CompArray,_carrays.push(_current)},unstack:function(){_current.variables.filter(function(v){v.unused&&warning(\"W098\",v.token,v.raw_text||v.value),v.undef&&state.funct[\"(scope)\"].block.use(v.value,v.token)}),_carrays.splice(-1,1),_current=_carrays[_carrays.length-1]},setState:function(s){_.contains([\"use\",\"define\",\"generate\",\"filter\"],s)&&(_current.mode=s)},check:function(v){return _current?_current&&\"use\"===_current.mode?(use(v)&&_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!0,unused:!1}),!0):_current&&\"define\"===_current.mode?(declare(v)||_current.variables.push({funct:state.funct,token:state.tokens.curr,value:v,undef:!1,unused:!0}),!0):_current&&\"generate\"===_current.mode?(state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):_current&&\"filter\"===_current.mode?(use(v)&&state.funct[\"(scope)\"].block.use(v,state.tokens.curr),!0):!1:void 0}}},escapeRegex=function(str){return str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g,\"\\\\$&\")},itself=function(s,o,g){function each(obj,cb){obj&&(Array.isArray(obj)||\"object\"!=typeof obj||(obj=Object.keys(obj)),obj.forEach(cb))}var i,k,x,reIgnoreStr,reIgnore,optionKeys,newOptionObj={},newIgnoredObj={};o=_.clone(o),state.reset(),o&&o.scope?JSHINT.scope=o.scope:(JSHINT.errors=[],JSHINT.undefs=[],JSHINT.internals=[],JSHINT.blacklist={},JSHINT.scope=\"(main)\"),predefined=Object.create(null),combine(predefined,vars.ecmaIdentifiers[3]),combine(predefined,vars.reservedVars),combine(predefined,g||{}),declared=Object.create(null);var exported=Object.create(null);if(o)for(each(o.predef||null,function(item){var slice,prop;\"-\"===item[0]?(slice=item.slice(1),JSHINT.blacklist[slice]=slice,delete predefined[slice]):(prop=Object.getOwnPropertyDescriptor(o.predef,item),predefined[item]=prop?prop.value:!1)}),each(o.exported||null,function(item){exported[item]=!0}),delete o.predef,delete o.exported,optionKeys=Object.keys(o),x=0;optionKeys.length>x;x++)if(/^-W\\d{3}$/g.test(optionKeys[x]))newIgnoredObj[optionKeys[x].slice(1)]=!0;else{var optionKey=optionKeys[x];newOptionObj[optionKey]=o[optionKey],(\"esversion\"===optionKey&&5===o[optionKey]||\"es5\"===optionKey&&o[optionKey])&&warning(\"I003\"),\"newcap\"===optionKeys[x]&&o[optionKey]===!1&&(newOptionObj[\"(explicitNewcap)\"]=!0)}state.option=newOptionObj,state.ignored=newIgnoredObj,state.option.indent=state.option.indent||4,state.option.maxerr=state.option.maxerr||50,indent=1;var scopeManagerInst=scopeManager(state,predefined,exported,declared);if(scopeManagerInst.on(\"warning\",function(ev){warning.apply(null,[ev.code,ev.token].concat(ev.data))}),scopeManagerInst.on(\"error\",function(ev){error.apply(null,[ev.code,ev.token].concat(ev.data))}),state.funct=functor(\"(global)\",null,{\"(global)\":!0,\"(scope)\":scopeManagerInst,\"(comparray)\":arrayComprehension(),\"(metrics)\":createMetrics(state.tokens.next)}),functions=[state.funct],urls=[],stack=null,member={},membersOnly=null,inblock=!1,lookahead=[],!isString(s)&&!Array.isArray(s))return errorAt(\"E004\",0),!1;api={get isJSON(){return state.jsonMode},getOption:function(name){return state.option[name]||null},getCache:function(name){return state.cache[name]},setCache:function(name,value){state.cache[name]=value},warn:function(code,data){warningAt.apply(null,[code,data.line,data.char].concat(data.data))},on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)}.bind(this))}},emitter.removeAllListeners(),(extraModules||[]).forEach(function(func){func(api)}),state.tokens.prev=state.tokens.curr=state.tokens.next=state.syntax[\"(begin)\"],o&&o.ignoreDelimiters&&(Array.isArray(o.ignoreDelimiters)||(o.ignoreDelimiters=[o.ignoreDelimiters]),o.ignoreDelimiters.forEach(function(delimiterPair){delimiterPair.start&&delimiterPair.end&&(reIgnoreStr=escapeRegex(delimiterPair.start)+\"[\\\\s\\\\S]*?\"+escapeRegex(delimiterPair.end),reIgnore=RegExp(reIgnoreStr,\"ig\"),s=s.replace(reIgnore,function(match){return match.replace(/./g,\" \")}))})),lex=new Lexer(s),lex.on(\"warning\",function(ev){warningAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"error\",function(ev){errorAt.apply(null,[ev.code,ev.line,ev.character].concat(ev.data))}),lex.on(\"fatal\",function(ev){quit(\"E041\",ev.line,ev.from)}),lex.on(\"Identifier\",function(ev){emitter.emit(\"Identifier\",ev)}),lex.on(\"String\",function(ev){emitter.emit(\"String\",ev)}),lex.on(\"Number\",function(ev){emitter.emit(\"Number\",ev)}),lex.start();for(var name in o)_.has(o,name)&&checkOption(name,state.tokens.curr);assume(),combine(predefined,g||{}),comma.first=!0;try{switch(advance(),state.tokens.next.id){case\"{\":case\"[\":destructuringAssignOrJsonValue();break;default:directives(),state.directive[\"use strict\"]&&\"global\"!==state.option.strict&&warning(\"W097\",state.tokens.prev),statements()}\"(end)\"!==state.tokens.next.id&&quit(\"E041\",state.tokens.curr.line),state.funct[\"(scope)\"].unstack()}catch(err){if(!err||\"JSHintError\"!==err.name)throw err;var nt=state.tokens.next||{};JSHINT.errors.push({scope:\"(main)\",raw:err.raw,code:err.code,reason:err.message,line:err.line||nt.line,character:err.character||nt.from},null)}if(\"(main)\"===JSHINT.scope)for(o=o||{},i=0;JSHINT.internals.length>i;i+=1)k=JSHINT.internals[i],o.scope=k.elem,itself(k.value,o,g);return 0===JSHINT.errors.length};return itself.addModule=function(func){extraModules.push(func)},itself.addModule(style.register),itself.data=function(){var fu,f,i,j,n,globals,data={functions:[],options:state.option};itself.errors.length&&(data.errors=itself.errors),state.jsonMode&&(data.json=!0);var impliedGlobals=state.funct[\"(scope)\"].getImpliedGlobals();for(impliedGlobals.length>0&&(data.implieds=impliedGlobals),urls.length>0&&(data.urls=urls),globals=state.funct[\"(scope)\"].getUsedOrDefinedGlobals(),globals.length>0&&(data.globals=globals),i=1;functions.length>i;i+=1){for(f=functions[i],fu={},j=0;functionicity.length>j;j+=1)fu[functionicity[j]]=[];for(j=0;functionicity.length>j;j+=1)0===fu[functionicity[j]].length&&delete fu[functionicity[j]];fu.name=f[\"(name)\"],fu.param=f[\"(params)\"],fu.line=f[\"(line)\"],fu.character=f[\"(character)\"],fu.last=f[\"(last)\"],fu.lastcharacter=f[\"(lastcharacter)\"],fu.metrics={complexity:f[\"(metrics)\"].ComplexityCount,parameters:f[\"(metrics)\"].arity,statements:f[\"(metrics)\"].statementCount},data.functions.push(fu)}var unuseds=state.funct[\"(scope)\"].getUnuseds();unuseds.length>0&&(data.unused=unuseds);for(n in member)if(\"number\"==typeof member[n]){data.member=member;break}return data},itself.jshint=itself,itself}();\"object\"==typeof exports&&exports&&(exports.JSHINT=JSHINT)},{\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./lex.js\":\"/node_modules/jshint/src/lex.js\",\"./messages.js\":\"/node_modules/jshint/src/messages.js\",\"./options.js\":\"/node_modules/jshint/src/options.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./scope-manager.js\":\"/node_modules/jshint/src/scope-manager.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",\"./style.js\":\"/node_modules/jshint/src/style.js\",\"./vars.js\":\"/node_modules/jshint/src/vars.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/lex.js\":[function(_dereq_,module,exports){\"use strict\";function asyncTrigger(){var _checks=[];return{push:function(fn){_checks.push(fn)},check:function(){for(var check=0;_checks.length>check;++check)_checks[check]();_checks.splice(0,_checks.length)}}}function Lexer(source){var lines=source;\"string\"==typeof lines&&(lines=lines.replace(/\\r\\n/g,\"\\n\").replace(/\\r/g,\"\\n\").split(\"\\n\")),lines[0]&&\"#!\"===lines[0].substr(0,2)&&(-1!==lines[0].indexOf(\"node\")&&(state.option.node=!0),lines[0]=\"\"),this.emitter=new events.EventEmitter,this.source=source,this.setLines(lines),this.prereg=!0,this.line=0,this.char=1,this.from=1,this.input=\"\",this.inComment=!1,this.context=[],this.templateStarts=[];for(var i=0;state.option.indent>i;i+=1)state.tab+=\" \";this.ignoreLinterErrors=!1}var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),reg=_dereq_(\"./reg.js\"),state=_dereq_(\"./state.js\").state,unicodeData=_dereq_(\"../data/ascii-identifier-data.js\"),asciiIdentifierStartTable=unicodeData.asciiIdentifierStartTable,asciiIdentifierPartTable=unicodeData.asciiIdentifierPartTable,Token={Identifier:1,Punctuator:2,NumericLiteral:3,StringLiteral:4,Comment:5,Keyword:6,NullLiteral:7,BooleanLiteral:8,RegExp:9,TemplateHead:10,TemplateMiddle:11,TemplateTail:12,NoSubstTemplate:13},Context={Block:1,Template:2};Lexer.prototype={_lines:[],inContext:function(ctxType){return this.context.length>0&&this.context[this.context.length-1].type===ctxType},pushContext:function(ctxType){this.context.push({type:ctxType})},popContext:function(){return this.context.pop()},isContext:function(context){return this.context.length>0&&this.context[this.context.length-1]===context},currentContext:function(){return this.context.length>0&&this.context[this.context.length-1]},getLines:function(){return this._lines=state.lines,this._lines},setLines:function(val){this._lines=val,state.lines=this._lines},peek:function(i){return this.input.charAt(i||0)},skip:function(i){i=i||1,this.char+=i,this.input=this.input.slice(i)},on:function(names,listener){names.split(\" \").forEach(function(name){this.emitter.on(name,listener)}.bind(this))},trigger:function(){this.emitter.emit.apply(this.emitter,Array.prototype.slice.call(arguments))},triggerAsync:function(type,args,checks,fn){checks.push(function(){fn()&&this.trigger(type,args)}.bind(this))},scanPunctuator:function(){var ch2,ch3,ch4,ch1=this.peek();switch(ch1){case\".\":if(/^[0-9]$/.test(this.peek(1)))return null;if(\".\"===this.peek(1)&&\".\"===this.peek(2))return{type:Token.Punctuator,value:\"...\"};case\"(\":case\")\":case\";\":case\",\":case\"[\":case\"]\":case\":\":case\"~\":case\"?\":return{type:Token.Punctuator,value:ch1};case\"{\":return this.pushContext(Context.Block),{type:Token.Punctuator,value:ch1};case\"}\":return this.inContext(Context.Block)&&this.popContext(),{type:Token.Punctuator,value:ch1};case\"#\":return{type:Token.Punctuator,value:ch1};case\"\":return null}return ch2=this.peek(1),ch3=this.peek(2),ch4=this.peek(3),\">\"===ch1&&\">\"===ch2&&\">\"===ch3&&\"=\"===ch4?{type:Token.Punctuator,value:\">>>=\"}:\"=\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"===\"}:\"!\"===ch1&&\"=\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"!==\"}:\">\"===ch1&&\">\"===ch2&&\">\"===ch3?{type:Token.Punctuator,value:\">>>\"}:\"<\"===ch1&&\"<\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\"<<=\"}:\">\"===ch1&&\">\"===ch2&&\"=\"===ch3?{type:Token.Punctuator,value:\">>=\"}:\"=\"===ch1&&\">\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:ch1===ch2&&\"+-<>&|\".indexOf(ch1)>=0?{type:Token.Punctuator,value:ch1+ch2}:\"<>=!+-*%&|^\".indexOf(ch1)>=0?\"=\"===ch2?{type:Token.Punctuator,value:ch1+ch2}:{type:Token.Punctuator,value:ch1}:\"/\"===ch1?\"=\"===ch2?{type:Token.Punctuator,value:\"/=\"}:{type:Token.Punctuator,value:\"/\"}:null},scanComments:function(){function commentToken(label,body,opt){var special=[\"jshint\",\"jslint\",\"members\",\"member\",\"globals\",\"global\",\"exported\"],isSpecial=!1,value=label+body,commentType=\"plain\";return opt=opt||{},opt.isMultiline&&(value+=\"*/\"),body=body.replace(/\\n/g,\" \"),\"/*\"===label&&reg.fallsThrough.test(body)&&(isSpecial=!0,commentType=\"falls through\"),special.forEach(function(str){if(!isSpecial&&(\"//\"!==label||\"jshint\"===str)&&(\" \"===body.charAt(str.length)&&body.substr(0,str.length)===str&&(isSpecial=!0,label+=str,body=body.substr(str.length)),isSpecial||\" \"!==body.charAt(0)||\" \"!==body.charAt(str.length+1)||body.substr(1,str.length)!==str||(isSpecial=!0,label=label+\" \"+str,body=body.substr(str.length+1)),isSpecial))switch(str){case\"member\":commentType=\"members\";break;case\"global\":commentType=\"globals\";break;default:var options=body.split(\":\").map(function(v){return v.replace(/^\\s+/,\"\").replace(/\\s+$/,\"\")});if(2===options.length)switch(options[0]){case\"ignore\":switch(options[1]){case\"start\":self.ignoringLinterErrors=!0,isSpecial=!1;break;case\"end\":self.ignoringLinterErrors=!1,isSpecial=!1}}commentType=str}}),{type:Token.Comment,commentType:commentType,value:value,body:body,isSpecial:isSpecial,isMultiline:opt.isMultiline||!1,isMalformed:opt.isMalformed||!1}}var ch1=this.peek(),ch2=this.peek(1),rest=this.input.substr(2),startLine=this.line,startChar=this.char,self=this;if(\"*\"===ch1&&\"/\"===ch2)return this.trigger(\"error\",{code:\"E018\",line:startLine,character:startChar}),this.skip(2),null;if(\"/\"!==ch1||\"*\"!==ch2&&\"/\"!==ch2)return null;if(\"/\"===ch2)return this.skip(this.input.length),commentToken(\"//\",rest);var body=\"\";if(\"*\"===ch2){for(this.inComment=!0,this.skip(2);\"*\"!==this.peek()||\"/\"!==this.peek(1);)if(\"\"===this.peek()){if(body+=\"\\n\",!this.nextLine())return this.trigger(\"error\",{code:\"E017\",line:startLine,character:startChar}),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0,isMalformed:!0})}else body+=this.peek(),this.skip();return this.skip(2),this.inComment=!1,commentToken(\"/*\",body,{isMultiline:!0})}},scanKeyword:function(){var result=/^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input),keywords=[\"if\",\"in\",\"do\",\"var\",\"for\",\"new\",\"try\",\"let\",\"this\",\"else\",\"case\",\"void\",\"with\",\"enum\",\"while\",\"break\",\"catch\",\"throw\",\"const\",\"yield\",\"class\",\"super\",\"return\",\"typeof\",\"delete\",\"switch\",\"export\",\"import\",\"default\",\"finally\",\"extends\",\"function\",\"continue\",\"debugger\",\"instanceof\"];return result&&keywords.indexOf(result[0])>=0?{type:Token.Keyword,value:result[0]}:null},scanIdentifier:function(){function isNonAsciiIdentifierStart(code){return code>256}function isNonAsciiIdentifierPart(code){return code>256}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function removeEscapeSequences(id){return id.replace(/\\\\u([0-9a-fA-F]{4})/g,function(m0,codepoint){return String.fromCharCode(parseInt(codepoint,16))})}var type,char,id=\"\",index=0,readUnicodeEscapeSequence=function(){if(index+=1,\"u\"!==this.peek(index))return null;var code,ch1=this.peek(index+1),ch2=this.peek(index+2),ch3=this.peek(index+3),ch4=this.peek(index+4);return isHexDigit(ch1)&&isHexDigit(ch2)&&isHexDigit(ch3)&&isHexDigit(ch4)?(code=parseInt(ch1+ch2+ch3+ch4,16),asciiIdentifierPartTable[code]||isNonAsciiIdentifierPart(code)?(index+=5,\"\\\\u\"+ch1+ch2+ch3+ch4):null):null}.bind(this),getIdentifierStart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierStartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierStart(code)?(index+=1,chr):null}.bind(this),getIdentifierPart=function(){var chr=this.peek(index),code=chr.charCodeAt(0);return 92===code?readUnicodeEscapeSequence():128>code?asciiIdentifierPartTable[code]?(index+=1,chr):null:isNonAsciiIdentifierPart(code)?(index+=1,chr):null}.bind(this);if(char=getIdentifierStart(),null===char)return null;for(id=char;char=getIdentifierPart(),null!==char;)id+=char;switch(id){case\"true\":case\"false\":type=Token.BooleanLiteral;break;case\"null\":type=Token.NullLiteral;break;default:type=Token.Identifier}return{type:type,value:removeEscapeSequences(id),text:id,tokenLength:id.length}},scanNumericLiteral:function(){function isDecimalDigit(str){return/^[0-9]$/.test(str)}function isOctalDigit(str){return/^[0-7]$/.test(str)}function isBinaryDigit(str){return/^[01]$/.test(str)}function isHexDigit(str){return/^[0-9a-fA-F]$/.test(str)}function isIdentifierStart(ch){return\"$\"===ch||\"_\"===ch||\"\\\\\"===ch||ch>=\"a\"&&\"z\">=ch||ch>=\"A\"&&\"Z\">=ch}var bad,index=0,value=\"\",length=this.input.length,char=this.peek(index),isAllowedDigit=isDecimalDigit,base=10,isLegacy=!1;if(\".\"!==char&&!isDecimalDigit(char))return null;if(\".\"!==char){for(value=this.peek(index),index+=1,char=this.peek(index),\"0\"===value&&((\"x\"===char||\"X\"===char)&&(isAllowedDigit=isHexDigit,base=16,index+=1,value+=char),(\"o\"===char||\"O\"===char)&&(isAllowedDigit=isOctalDigit,base=8,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Octal integer literal\",\"6\"]}),index+=1,value+=char),(\"b\"===char||\"B\"===char)&&(isAllowedDigit=isBinaryDigit,base=2,state.inES6(!0)||this.trigger(\"warning\",{code:\"W119\",line:this.line,character:this.char,data:[\"Binary integer literal\",\"6\"]}),index+=1,value+=char),isOctalDigit(char)&&(isAllowedDigit=isOctalDigit,base=8,isLegacy=!0,bad=!1,index+=1,value+=char),!isOctalDigit(char)&&isDecimalDigit(char)&&(index+=1,value+=char));length>index;){if(char=this.peek(index),isLegacy&&isDecimalDigit(char))bad=!0;else if(!isAllowedDigit(char))break;value+=char,index+=1}if(isAllowedDigit!==isDecimalDigit)return!isLegacy&&2>=value.length?{type:Token.NumericLiteral,value:value,isMalformed:!0}:length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isLegacy:isLegacy,isMalformed:!1}}if(\".\"===char)for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1;if(\"e\"===char||\"E\"===char){if(value+=char,index+=1,char=this.peek(index),(\"+\"===char||\"-\"===char)&&(value+=this.peek(index),index+=1),char=this.peek(index),!isDecimalDigit(char))return null;for(value+=char,index+=1;length>index&&(char=this.peek(index),isDecimalDigit(char));)value+=char,index+=1}return length>index&&(char=this.peek(index),isIdentifierStart(char))?null:{type:Token.NumericLiteral,value:value,base:base,isMalformed:!isFinite(value)}},scanEscapeSequence:function(checks){var allowNewLine=!1,jump=1;this.skip();var char=this.peek();switch(char){case\"'\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\'\"]},checks,function(){return state.jsonMode});break;case\"b\":char=\"\\\\b\";break;case\"f\":char=\"\\\\f\";break;case\"n\":char=\"\\\\n\";break;case\"r\":char=\"\\\\r\";break;case\"t\":char=\"\\\\t\";break;case\"0\":char=\"\\\\0\";var n=parseInt(this.peek(1),10);this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return n>=0&&7>=n&&state.isStrict()});break;case\"u\":var hexCode=this.input.substr(1,4),code=parseInt(hexCode,16);isNaN(code)&&this.trigger(\"warning\",{code:\"W052\",line:this.line,character:this.char,data:[\"u\"+hexCode]}),char=String.fromCharCode(code),jump=5;break;case\"v\":this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\v\"]},checks,function(){return state.jsonMode}),char=\"\u000b\";break;case\"x\":var x=parseInt(this.input.substr(1,2),16);this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"\\\\x-\"]},checks,function(){return state.jsonMode}),char=String.fromCharCode(x),jump=3;break;case\"\\\\\":char=\"\\\\\\\\\";break;case'\"':char='\\\\\"';break;case\"/\":break;case\"\":allowNewLine=!0,char=\"\"}return{\"char\":char,jump:jump,allowNewLine:allowNewLine}},scanTemplateLiteral:function(checks){var tokenType,ch,value=\"\",startLine=this.line,startChar=this.char,depth=this.templateStarts.length;if(!state.inES6(!0))return null;if(\"`\"===this.peek())tokenType=Token.TemplateHead,this.templateStarts.push({line:this.line,\"char\":this.char}),depth=this.templateStarts.length,this.skip(1),this.pushContext(Context.Template);else{if(!this.inContext(Context.Template)||\"}\"!==this.peek())return null;tokenType=Token.TemplateMiddle}for(;\"`\"!==this.peek();){for(;\"\"===(ch=this.peek());)if(value+=\"\\n\",!this.nextLine()){var startPos=this.templateStarts.pop();return this.trigger(\"error\",{code:\"E052\",line:startPos.line,character:startPos.char}),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,depth:depth,context:this.popContext()}}if(\"$\"===ch&&\"{\"===this.peek(1))return value+=\"${\",this.skip(2),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.currentContext()};\nif(\"\\\\\"===ch){var escape=this.scanEscapeSequence(checks);value+=escape.char,this.skip(escape.jump)}else\"`\"!==ch&&(value+=ch,this.skip(1))}return tokenType=tokenType===Token.TemplateHead?Token.NoSubstTemplate:Token.TemplateTail,this.skip(1),this.templateStarts.pop(),{type:tokenType,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,depth:depth,context:this.popContext()}},scanStringLiteral:function(checks){var quote=this.peek();if('\"'!==quote&&\"'\"!==quote)return null;this.triggerAsync(\"warning\",{code:\"W108\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&'\"'!==quote});var value=\"\",startLine=this.line,startChar=this.char,allowNewLine=!1;for(this.skip();this.peek()!==quote;)if(\"\"===this.peek()){if(allowNewLine?(allowNewLine=!1,this.triggerAsync(\"warning\",{code:\"W043\",line:this.line,character:this.char},checks,function(){return!state.option.multistr}),this.triggerAsync(\"warning\",{code:\"W042\",line:this.line,character:this.char},checks,function(){return state.jsonMode&&state.option.multistr})):this.trigger(\"warning\",{code:\"W112\",line:this.line,character:this.char}),!this.nextLine())return this.trigger(\"error\",{code:\"E029\",line:startLine,character:startChar}),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!0,quote:quote}}else{allowNewLine=!1;var char=this.peek(),jump=1;if(\" \">char&&this.trigger(\"warning\",{code:\"W113\",line:this.line,character:this.char,data:[\"<non-printable>\"]}),\"\\\\\"===char){var parsed=this.scanEscapeSequence(checks);char=parsed.char,jump=parsed.jump,allowNewLine=parsed.allowNewLine}value+=char,this.skip(jump)}return this.skip(),{type:Token.StringLiteral,value:value,startLine:startLine,startChar:startChar,isUnclosed:!1,quote:quote}},scanRegExp:function(){var terminated,index=0,length=this.input.length,char=this.peek(),value=char,body=\"\",flags=[],malformed=!1,isCharSet=!1,scanUnexpectedChars=function(){\" \">char&&(malformed=!0,this.trigger(\"warning\",{code:\"W048\",line:this.line,character:this.char})),\"<\"===char&&(malformed=!0,this.trigger(\"warning\",{code:\"W049\",line:this.line,character:this.char,data:[char]}))}.bind(this);if(!this.prereg||\"/\"!==char)return null;for(index+=1,terminated=!1;length>index;)if(char=this.peek(index),value+=char,body+=char,isCharSet)\"]\"===char&&(\"\\\\\"!==this.peek(index-1)||\"\\\\\"===this.peek(index-2))&&(isCharSet=!1),\"\\\\\"===char&&(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars()),index+=1;else{if(\"\\\\\"===char){if(index+=1,char=this.peek(index),body+=char,value+=char,scanUnexpectedChars(),\"/\"===char){index+=1;continue}if(\"[\"===char){index+=1;continue}}if(\"[\"!==char){if(\"/\"===char){body=body.substr(0,body.length-1),terminated=!0,index+=1;break}index+=1}else isCharSet=!0,index+=1}if(!terminated)return this.trigger(\"error\",{code:\"E015\",line:this.line,character:this.from}),void this.trigger(\"fatal\",{line:this.line,from:this.from});for(;length>index&&(char=this.peek(index),/[gim]/.test(char));)flags.push(char),value+=char,index+=1;try{RegExp(body,flags.join(\"\"))}catch(err){malformed=!0,this.trigger(\"error\",{code:\"E016\",line:this.line,character:this.char,data:[err.message]})}return{type:Token.RegExp,value:value,flags:flags,isMalformed:malformed}},scanNonBreakingSpaces:function(){return state.option.nonbsp?this.input.search(/(\\u00A0)/):-1},scanUnsafeChars:function(){return this.input.search(reg.unsafeChars)},next:function(checks){this.from=this.char;var start;if(/\\s/.test(this.peek()))for(start=this.char;/\\s/.test(this.peek());)this.from+=1,this.skip();var match=this.scanComments()||this.scanStringLiteral(checks)||this.scanTemplateLiteral(checks);return match?match:(match=this.scanRegExp()||this.scanPunctuator()||this.scanKeyword()||this.scanIdentifier()||this.scanNumericLiteral(),match?(this.skip(match.tokenLength||match.value.length),match):null)},nextLine:function(){var char;if(this.line>=this.getLines().length)return!1;this.input=this.getLines()[this.line],this.line+=1,this.char=1,this.from=1;var inputTrimmed=this.input.trim(),startsWith=function(){return _.some(arguments,function(prefix){return 0===inputTrimmed.indexOf(prefix)})},endsWith=function(){return _.some(arguments,function(suffix){return-1!==inputTrimmed.indexOf(suffix,inputTrimmed.length-suffix.length)})};if(this.ignoringLinterErrors===!0&&(startsWith(\"/*\",\"//\")||this.inComment&&endsWith(\"*/\")||(this.input=\"\")),char=this.scanNonBreakingSpaces(),char>=0&&this.trigger(\"warning\",{code:\"W125\",line:this.line,character:char+1}),this.input=this.input.replace(/\\t/g,state.tab),char=this.scanUnsafeChars(),char>=0&&this.trigger(\"warning\",{code:\"W100\",line:this.line,character:char}),!this.ignoringLinterErrors&&state.option.maxlen&&state.option.maxlen<this.input.length){var inComment=this.inComment||startsWith.call(inputTrimmed,\"//\")||startsWith.call(inputTrimmed,\"/*\"),shouldTriggerError=!inComment||!reg.maxlenException.test(inputTrimmed);shouldTriggerError&&this.trigger(\"warning\",{code:\"W101\",line:this.line,character:this.input.length})}return!0},start:function(){this.nextLine()},token:function(){function isReserved(token,isProperty){if(!token.reserved)return!1;var meta=token.meta;if(meta&&meta.isFutureReservedWord&&state.inES5()){if(!meta.es5)return!1;if(meta.strictOnly&&!state.option.strict&&!state.isStrict())return!1;if(isProperty)return!1}return!0}for(var token,checks=asyncTrigger(),create=function(type,value,isProperty,token){var obj;if(\"(endline)\"!==type&&\"(end)\"!==type&&(this.prereg=!1),\"(punctuator)\"===type){switch(value){case\".\":case\")\":case\"~\":case\"#\":case\"]\":case\"++\":case\"--\":this.prereg=!1;break;default:this.prereg=!0}obj=Object.create(state.syntax[value]||state.syntax[\"(error)\"])}return\"(identifier)\"===type&&((\"return\"===value||\"case\"===value||\"typeof\"===value)&&(this.prereg=!0),_.has(state.syntax,value)&&(obj=Object.create(state.syntax[value]||state.syntax[\"(error)\"]),isReserved(obj,isProperty&&\"(identifier)\"===type)||(obj=null))),obj||(obj=Object.create(state.syntax[type])),obj.identifier=\"(identifier)\"===type,obj.type=obj.type||type,obj.value=value,obj.line=this.line,obj.character=this.char,obj.from=this.from,obj.identifier&&token&&(obj.raw_text=token.text||token.value),token&&token.startLine&&token.startLine!==this.line&&(obj.startLine=token.startLine),token&&token.context&&(obj.context=token.context),token&&token.depth&&(obj.depth=token.depth),token&&token.isUnclosed&&(obj.isUnclosed=token.isUnclosed),isProperty&&obj.identifier&&(obj.isProperty=isProperty),obj.check=checks.check,obj}.bind(this);;){if(!this.input.length)return this.nextLine()?create(\"(endline)\",\"\"):this.exhausted?null:(this.exhausted=!0,create(\"(end)\",\"\"));if(token=this.next(checks))switch(token.type){case Token.StringLiteral:return this.triggerAsync(\"String\",{line:this.line,\"char\":this.char,from:this.from,startLine:token.startLine,startChar:token.startChar,value:token.value,quote:token.quote},checks,function(){return!0}),create(\"(string)\",token.value,null,token);case Token.TemplateHead:return this.trigger(\"TemplateHead\",{line:this.line,\"char\":this.char,from:this.from,startLine:token.startLine,startChar:token.startChar,value:token.value}),create(\"(template)\",token.value,null,token);case Token.TemplateMiddle:return this.trigger(\"TemplateMiddle\",{line:this.line,\"char\":this.char,from:this.from,startLine:token.startLine,startChar:token.startChar,value:token.value}),create(\"(template middle)\",token.value,null,token);case Token.TemplateTail:return this.trigger(\"TemplateTail\",{line:this.line,\"char\":this.char,from:this.from,startLine:token.startLine,startChar:token.startChar,value:token.value}),create(\"(template tail)\",token.value,null,token);case Token.NoSubstTemplate:return this.trigger(\"NoSubstTemplate\",{line:this.line,\"char\":this.char,from:this.from,startLine:token.startLine,startChar:token.startChar,value:token.value}),create(\"(no subst template)\",token.value,null,token);case Token.Identifier:this.triggerAsync(\"Identifier\",{line:this.line,\"char\":this.char,from:this.form,name:token.value,raw_name:token.text,isProperty:\".\"===state.tokens.curr.id},checks,function(){return!0});case Token.Keyword:case Token.NullLiteral:case Token.BooleanLiteral:return create(\"(identifier)\",token.value,\".\"===state.tokens.curr.id,token);case Token.NumericLiteral:return token.isMalformed&&this.trigger(\"warning\",{code:\"W045\",line:this.line,character:this.char,data:[token.value]}),this.triggerAsync(\"warning\",{code:\"W114\",line:this.line,character:this.char,data:[\"0x-\"]},checks,function(){return 16===token.base&&state.jsonMode}),this.triggerAsync(\"warning\",{code:\"W115\",line:this.line,character:this.char},checks,function(){return state.isStrict()&&8===token.base&&token.isLegacy}),this.trigger(\"Number\",{line:this.line,\"char\":this.char,from:this.from,value:token.value,base:token.base,isMalformed:token.malformed}),create(\"(number)\",token.value);case Token.RegExp:return create(\"(regexp)\",token.value);case Token.Comment:if(state.tokens.curr.comment=!0,token.isSpecial)return{id:\"(comment)\",value:token.value,body:token.body,type:token.commentType,isSpecial:token.isSpecial,line:this.line,character:this.char,from:this.from};break;case\"\":break;default:return create(\"(punctuator)\",token.value)}else this.input.length&&(this.trigger(\"error\",{code:\"E024\",line:this.line,character:this.char,data:[this.peek()]}),this.input=\"\")}}},exports.Lexer=Lexer,exports.Context=Context},{\"../data/ascii-identifier-data.js\":\"/node_modules/jshint/data/ascii-identifier-data.js\",\"../lodash\":\"/node_modules/jshint/lodash.js\",\"./reg.js\":\"/node_modules/jshint/src/reg.js\",\"./state.js\":\"/node_modules/jshint/src/state.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/messages.js\":[function(_dereq_,module,exports){\"use strict\";var _=_dereq_(\"../lodash\"),errors={E001:\"Bad option: '{a}'.\",E002:\"Bad option value.\",E003:\"Expected a JSON value.\",E004:\"Input is neither a string nor an array of strings.\",E005:\"Input is empty.\",E006:\"Unexpected early end of program.\",E007:'Missing \"use strict\" statement.',E008:\"Strict violation.\",E009:\"Option 'validthis' can't be used in a global scope.\",E010:\"'with' is not allowed in strict mode.\",E011:\"'{a}' has already been declared.\",E012:\"const '{a}' is initialized to 'undefined'.\",E013:\"Attempting to override '{a}' which is a constant.\",E014:\"A regular expression literal can be confused with '/='.\",E015:\"Unclosed regular expression.\",E016:\"Invalid regular expression.\",E017:\"Unclosed comment.\",E018:\"Unbegun comment.\",E019:\"Unmatched '{a}'.\",E020:\"Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.\",E021:\"Expected '{a}' and instead saw '{b}'.\",E022:\"Line breaking error '{a}'.\",E023:\"Missing '{a}'.\",E024:\"Unexpected '{a}'.\",E025:\"Missing ':' on a case clause.\",E026:\"Missing '}' to match '{' from line {a}.\",E027:\"Missing ']' to match '[' from line {a}.\",E028:\"Illegal comma.\",E029:\"Unclosed string.\",E030:\"Expected an identifier and instead saw '{a}'.\",E031:\"Bad assignment.\",E032:\"Expected a small integer or 'false' and instead saw '{a}'.\",E033:\"Expected an operator and instead saw '{a}'.\",E034:\"get/set are ES5 features.\",E035:\"Missing property name.\",E036:\"Expected to see a statement and instead saw a block.\",E037:null,E038:null,E039:\"Function declarations are not invocable. Wrap the whole function invocation in parens.\",E040:\"Each value should have its own case label.\",E041:\"Unrecoverable syntax error.\",E042:\"Stopping.\",E043:\"Too many errors.\",E044:null,E045:\"Invalid for each loop.\",E046:\"A yield statement shall be within a generator function (with syntax: `function*`)\",E047:null,E048:\"{a} declaration not directly within block.\",E049:\"A {a} cannot be named '{b}'.\",E050:\"Mozilla acequires the yield expression to be parenthesized here.\",E051:null,E052:\"Unclosed template literal.\",E053:\"Export declaration must be in global scope.\",E054:\"Class properties must be methods. Expected '(' but instead saw '{a}'.\",E055:\"The '{a}' option cannot be set after any executable code.\",E056:\"'{a}' was used before it was declared, which is illegal for '{b}' variables.\",E057:\"Invalid meta property: '{a}.{b}'.\",E058:\"Missing semicolon.\"},warnings={W001:\"'hasOwnProperty' is a really bad name.\",W002:\"Value of '{a}' may be overwritten in IE 8 and earlier.\",W003:\"'{a}' was used before it was defined.\",W004:\"'{a}' is already defined.\",W005:\"A dot following a number can be confused with a decimal point.\",W006:\"Confusing minuses.\",W007:\"Confusing plusses.\",W008:\"A leading decimal point can be confused with a dot: '{a}'.\",W009:\"The array literal notation [] is preferable.\",W010:\"The object literal notation {} is preferable.\",W011:null,W012:null,W013:null,W014:\"Bad line breaking before '{a}'.\",W015:null,W016:\"Unexpected use of '{a}'.\",W017:\"Bad operand.\",W018:\"Confusing use of '{a}'.\",W019:\"Use the isNaN function to compare with NaN.\",W020:\"Read only.\",W021:\"Reassignment of '{a}', which is is a {b}. Use 'var' or 'let' to declare bindings that may change.\",W022:\"Do not assign to the exception parameter.\",W023:\"Expected an identifier in an assignment and instead saw a function invocation.\",W024:\"Expected an identifier and instead saw '{a}' (a reserved word).\",W025:\"Missing name in function declaration.\",W026:\"Inner functions should be listed at the top of the outer function.\",W027:\"Unreachable '{a}' after '{b}'.\",W028:\"Label '{a}' on {b} statement.\",W030:\"Expected an assignment or function call and instead saw an expression.\",W031:\"Do not use 'new' for side effects.\",W032:\"Unnecessary semicolon.\",W033:\"Missing semicolon.\",W034:'Unnecessary directive \"{a}\".',W035:\"Empty block.\",W036:\"Unexpected /*member '{a}'.\",W037:\"'{a}' is a statement label.\",W038:\"'{a}' used out of scope.\",W039:\"'{a}' is not allowed.\",W040:\"Possible strict violation.\",W041:\"Use '{a}' to compare with '{b}'.\",W042:\"Avoid EOL escaping.\",W043:\"Bad escaping of EOL. Use option multistr if needed.\",W044:\"Bad or unnecessary escaping.\",W045:\"Bad number '{a}'.\",W046:\"Don't use extra leading zeros '{a}'.\",W047:\"A trailing decimal point can be confused with a dot: '{a}'.\",W048:\"Unexpected control character in regular expression.\",W049:\"Unexpected escaped character '{a}' in regular expression.\",W050:\"JavaScript URL.\",W051:\"Variables should not be deleted.\",W052:\"Unexpected '{a}'.\",W053:\"Do not use {a} as a constructor.\",W054:\"The Function constructor is a form of eval.\",W055:\"A constructor name should start with an uppercase letter.\",W056:\"Bad constructor.\",W057:\"Weird construction. Is 'new' necessary?\",W058:\"Missing '()' invoking a constructor.\",W059:\"Avoid arguments.{a}.\",W060:\"document.write can be a form of eval.\",W061:\"eval can be harmful.\",W062:\"Wrap an immediate function invocation in parens to assist the reader in understanding that the expression is the result of a function, and not the function itself.\",W063:\"Math is not a function.\",W064:\"Missing 'new' prefix when invoking a constructor.\",W065:\"Missing radix parameter.\",W066:\"Implied eval. Consider passing a function instead of a string.\",W067:\"Bad invocation.\",W068:\"Wrapping non-IIFE function literals in parens is unnecessary.\",W069:\"['{a}'] is better written in dot notation.\",W070:\"Extra comma. (it breaks older versions of IE)\",W071:\"This function has too many statements. ({a})\",W072:\"This function has too many parameters. ({a})\",W073:\"Blocks are nested too deeply. ({a})\",W074:\"This function's cyclomatic complexity is too high. ({a})\",W075:\"Duplicate {a} '{b}'.\",W076:\"Unexpected parameter '{a}' in get {b} function.\",W077:\"Expected a single parameter in set {a} function.\",W078:\"Setter is defined without getter.\",W079:\"Redefinition of '{a}'.\",W080:\"It's not necessary to initialize '{a}' to 'undefined'.\",W081:null,W082:\"Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.\",W083:\"Don't make functions within a loop.\",W084:\"Assignment in conditional expression\",W085:\"Don't use 'with'.\",W086:\"Expected a 'break' statement before '{a}'.\",W087:\"Forgotten 'debugger' statement?\",W088:\"Creating global 'for' variable. Should be 'for (var {a} ...'.\",W089:\"The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.\",W090:\"'{a}' is not a statement label.\",W091:null,W093:\"Did you mean to return a conditional instead of an assignment?\",W094:\"Unexpected comma.\",W095:\"Expected a string and instead saw {a}.\",W096:\"The '{a}' key may produce unexpected results.\",W097:'Use the function form of \"use strict\".',W098:\"'{a}' is defined but never used.\",W099:null,W100:\"This character may get silently deleted by one or more browsers.\",W101:\"Line is too long.\",W102:null,W103:\"The '{a}' property is deprecated.\",W104:\"'{a}' is available in ES{b} (use 'esversion: {b}') or Mozilla JS extensions (use moz).\",W105:\"Unexpected {a} in '{b}'.\",W106:\"Identifier '{a}' is not in camel case.\",W107:\"Script URL.\",W108:\"Strings must use doublequote.\",W109:\"Strings must use singlequote.\",W110:\"Mixed double and single quotes.\",W112:\"Unclosed string.\",W113:\"Control character in string: {a}.\",W114:\"Avoid {a}.\",W115:\"Octal literals are not allowed in strict mode.\",W116:\"Expected '{a}' and instead saw '{b}'.\",W117:\"'{a}' is not defined.\",W118:\"'{a}' is only available in Mozilla JavaScript extensions (use moz option).\",W119:\"'{a}' is only available in ES{b} (use 'esversion: {b}').\",W120:\"You might be leaking a variable ({a}) here.\",W121:\"Extending prototype of native object: '{a}'.\",W122:\"Invalid typeof value '{a}'\",W123:\"'{a}' is already defined in outer scope.\",W124:\"A generator function shall contain a yield statement.\",W125:\"This line contains non-breaking spaces: http://jshint.com/doc/options/#nonbsp\",W126:\"Unnecessary grouping operator.\",W127:\"Unexpected use of a comma operator.\",W128:\"Empty array elements acequire elision=true.\",W129:\"'{a}' is defined in a future version of JavaScript. Use a different variable name to avoid migration issues.\",W130:\"Invalid element after rest element.\",W131:\"Invalid parameter after rest parameter.\",W132:\"`var` declarations are forbidden. Use `let` or `const` instead.\",W133:\"Invalid for-{a} loop left-hand-side: {b}.\",W134:\"The '{a}' option is only available when linting ECMAScript {b} code.\",W135:\"{a} may not be supported by non-browser environments.\",W136:\"'{a}' must be in function scope.\",W137:\"Empty destructuring.\",W138:\"Regular parameters should not come after default parameters.\"},info={I001:\"Comma warnings can be turned off with 'laxcomma'.\",I002:null,I003:\"ES5 option is now set per default\"};exports.errors={},exports.warnings={},exports.info={},_.each(errors,function(desc,code){exports.errors[code]={code:code,desc:desc}}),_.each(warnings,function(desc,code){exports.warnings[code]={code:code,desc:desc}}),_.each(info,function(desc,code){exports.info[code]={code:code,desc:desc}})},{\"../lodash\":\"/node_modules/jshint/lodash.js\"}],\"/node_modules/jshint/src/name-stack.js\":[function(_dereq_,module){\"use strict\";function NameStack(){this._stack=[]}Object.defineProperty(NameStack.prototype,\"length\",{get:function(){return this._stack.length}}),NameStack.prototype.push=function(){this._stack.push(null)},NameStack.prototype.pop=function(){this._stack.pop()},NameStack.prototype.set=function(token){this._stack[this.length-1]=token},NameStack.prototype.infer=function(){var type,nameToken=this._stack[this.length-1],prefix=\"\";return nameToken&&\"class\"!==nameToken.type||(nameToken=this._stack[this.length-2]),nameToken?(type=nameToken.type,\"(string)\"!==type&&\"(number)\"!==type&&\"(identifier)\"!==type&&\"default\"!==type?\"(expression)\":(nameToken.accessorType&&(prefix=nameToken.accessorType+\" \"),prefix+nameToken.value)):\"(empty)\"},module.exports=NameStack},{}],\"/node_modules/jshint/src/options.js\":[function(_dereq_,module,exports){\"use strict\";exports.bool={enforcing:{bitwise:!0,freeze:!0,camelcase:!0,curly:!0,eqeqeq:!0,futurehostile:!0,notypeof:!0,es3:!0,es5:!0,forin:!0,funcscope:!0,immed:!0,iterator:!0,newcap:!0,noarg:!0,nocomma:!0,noempty:!0,nonbsp:!0,nonew:!0,undef:!0,singleGroups:!1,varstmt:!1,enforceall:!1},relaxing:{asi:!0,multistr:!0,debug:!0,boss:!0,evil:!0,globalstrict:!0,plusplus:!0,proto:!0,scripturl:!0,sub:!0,supernew:!0,laxbreak:!0,laxcomma:!0,validthis:!0,withstmt:!0,moz:!0,noyield:!0,eqnull:!0,lastsemic:!0,loopfunc:!0,expr:!0,esnext:!0,elision:!0},environments:{mootools:!0,couch:!0,jasmine:!0,jquery:!0,node:!0,qunit:!0,rhino:!0,shelljs:!0,prototypejs:!0,yui:!0,mocha:!0,module:!0,wsh:!0,worker:!0,nonstandard:!0,browser:!0,browserify:!0,devel:!0,dojo:!0,typed:!0,phantom:!0},obsolete:{onecase:!0,regexp:!0,regexdash:!0}},exports.val={maxlen:!1,indent:!1,maxerr:!1,predef:!1,globals:!1,quotmark:!1,scope:!1,maxstatements:!1,maxdepth:!1,maxparams:!1,maxcomplexity:!1,shadow:!1,strict:!0,unused:!0,latedef:!1,ignore:!1,ignoreDelimiters:!1,esversion:5},exports.inverted={bitwise:!0,forin:!0,newcap:!0,plusplus:!0,regexp:!0,undef:!0,eqeqeq:!0,strict:!0},exports.validNames=Object.keys(exports.val).concat(Object.keys(exports.bool.relaxing)).concat(Object.keys(exports.bool.enforcing)).concat(Object.keys(exports.bool.obsolete)).concat(Object.keys(exports.bool.environments)),exports.renamed={eqeq:\"eqeqeq\",windows:\"wsh\",sloppy:\"strict\"},exports.removed={nomen:!0,onevar:!0,passfail:!0,white:!0,gcl:!0,smarttabs:!0,trailing:!0},exports.noenforceall={varstmt:!0,strict:!0}},{}],\"/node_modules/jshint/src/reg.js\":[function(_dereq_,module,exports){\"use strict\";exports.unsafeString=/@cc|<\\/?|script|\\]\\s*\\]|<\\s*!|&lt/i,exports.unsafeChars=/[\\u0000-\\u001f\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/,exports.needEsc=/[\\u0000-\\u001f&<\"\\/\\\\\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/,exports.needEscGlobal=/[\\u0000-\\u001f&<\"\\/\\\\\\u007f-\\u009f\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g,exports.starSlash=/\\*\\//,exports.identifier=/^([a-zA-Z_$][a-zA-Z0-9_$]*)$/,exports.javascriptURL=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i,exports.fallsThrough=/^\\s*falls?\\sthrough\\s*$/,exports.maxlenException=/^(?:(?:\\/\\/|\\/\\*|\\*) ?)?[^ ]+$/},{}],\"/node_modules/jshint/src/scope-manager.js\":[function(_dereq_,module){\"use strict\";var _=_dereq_(\"../lodash\"),events=_dereq_(\"events\"),marker={},scopeManager=function(state,predefined,exported,declared){function _newScope(type){_current={\"(labels)\":Object.create(null),\"(usages)\":Object.create(null),\"(breakLabels)\":Object.create(null),\"(parent)\":_current,\"(type)\":type,\"(params)\":\"functionparams\"===type||\"catchparams\"===type?[]:null},_scopeStack.push(_current)}function warning(code,token){emitter.emit(\"warning\",{code:code,token:token,data:_.slice(arguments,2)})}function error(code,token){emitter.emit(\"warning\",{code:code,token:token,data:_.slice(arguments,2)})}function _setupUsages(labelName){_current[\"(usages)\"][labelName]||(_current[\"(usages)\"][labelName]={\"(modified)\":[],\"(reassigned)\":[],\"(tokens)\":[]})}function _checkForUnused(){if(\"functionparams\"===_current[\"(type)\"])return _checkParams(),void 0;var curentLabels=_current[\"(labels)\"];for(var labelName in curentLabels)curentLabels[labelName]&&\"exception\"!==curentLabels[labelName][\"(type)\"]&&curentLabels[labelName][\"(unused)\"]&&_warnUnused(labelName,curentLabels[labelName][\"(token)\"],\"var\")}function _checkParams(){var params=_current[\"(params)\"];if(params)for(var unused_opt,param=params.pop();param;){var label=_current[\"(labels)\"][param];if(unused_opt=_getUnusedOption(state.funct[\"(unusedOption)\"]),\"undefined\"===param)return;if(label[\"(unused)\"])_warnUnused(param,label[\"(token)\"],\"param\",state.funct[\"(unusedOption)\"]);else if(\"last-param\"===unused_opt)return;param=params.pop()}}function _getLabel(labelName){for(var i=_scopeStack.length-1;i>=0;--i){var scopeLabels=_scopeStack[i][\"(labels)\"];if(scopeLabels[labelName])return scopeLabels}}function usedSoFarInCurrentFunction(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(usages)\"][labelName])return current[\"(usages)\"][labelName];if(current===_currentFunctBody)break}return!1}function _checkOuterShadow(labelName,token){if(\"outer\"===state.option.shadow)for(var isGlobal=\"global\"===_currentFunctBody[\"(type)\"],isNewFunction=\"functionparams\"===_current[\"(type)\"],outsideCurrentFunction=!isGlobal,i=0;_scopeStack.length>i;i++){var stackItem=_scopeStack[i];isNewFunction||_scopeStack[i+1]!==_currentFunctBody||(outsideCurrentFunction=!1),outsideCurrentFunction&&stackItem[\"(labels)\"][labelName]&&warning(\"W123\",token,labelName),stackItem[\"(breakLabels)\"][labelName]&&warning(\"W123\",token,labelName)}}function _latedefWarning(type,labelName,token){state.option.latedef&&(state.option.latedef===!0&&\"function\"===type||\"function\"!==type)&&warning(\"W003\",token,labelName)}var _current,_scopeStack=[];_newScope(\"global\"),_current[\"(predefined)\"]=predefined;var _currentFunctBody=_current,usedPredefinedAndGlobals=Object.create(null),impliedGlobals=Object.create(null),unuseds=[],emitter=new events.EventEmitter,_getUnusedOption=function(unused_opt){return void 0===unused_opt&&(unused_opt=state.option.unused),unused_opt===!0&&(unused_opt=\"last-param\"),unused_opt},_warnUnused=function(name,tkn,type,unused_opt){var line=tkn.line,chr=tkn.from,raw_name=tkn.raw_text||name;unused_opt=_getUnusedOption(unused_opt);var warnable_types={vars:[\"var\"],\"last-param\":[\"var\",\"param\"],strict:[\"var\",\"param\",\"last-param\"]};unused_opt&&warnable_types[unused_opt]&&-1!==warnable_types[unused_opt].indexOf(type)&&warning(\"W098\",{line:line,from:chr},raw_name),(unused_opt||\"var\"===type)&&unuseds.push({name:name,line:line,character:chr})},scopeManagerInst={on:function(names,listener){names.split(\" \").forEach(function(name){emitter.on(name,listener)})},isPredefined:function(labelName){return!this.has(labelName)&&_.has(_scopeStack[0][\"(predefined)\"],labelName)},stack:function(type){var previousScope=_current;_newScope(type),type||\"functionparams\"!==previousScope[\"(type)\"]||(_current[\"(isFuncBody)\"]=!0,_current[\"(context)\"]=_currentFunctBody,_currentFunctBody=_current)},unstack:function(){var i,j,subScope=_scopeStack.length>1?_scopeStack[_scopeStack.length-2]:null,isUnstackingFunctionBody=_current===_currentFunctBody,isUnstackingFunctionParams=\"functionparams\"===_current[\"(type)\"],isUnstackingFunctionOuter=\"functionouter\"===_current[\"(type)\"],currentUsages=_current[\"(usages)\"],currentLabels=_current[\"(labels)\"],usedLabelNameList=Object.keys(currentUsages);for(currentUsages.__proto__&&-1===usedLabelNameList.indexOf(\"__proto__\")&&usedLabelNameList.push(\"__proto__\"),i=0;usedLabelNameList.length>i;i++){var usedLabelName=usedLabelNameList[i],usage=currentUsages[usedLabelName],usedLabel=currentLabels[usedLabelName];if(usedLabel){var usedLabelType=usedLabel[\"(type)\"];if(usedLabel[\"(useOutsideOfScope)\"]&&!state.option.funcscope){var usedTokens=usage[\"(tokens)\"];if(usedTokens)for(j=0;usedTokens.length>j;j++)usedLabel[\"(function)\"]===usedTokens[j][\"(function)\"]&&error(\"W038\",usedTokens[j],usedLabelName)}if(_current[\"(labels)\"][usedLabelName][\"(unused)\"]=!1,\"const\"===usedLabelType&&usage[\"(modified)\"])for(j=0;usage[\"(modified)\"].length>j;j++)error(\"E013\",usage[\"(modified)\"][j],usedLabelName);if((\"function\"===usedLabelType||\"class\"===usedLabelType)&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)error(\"W021\",usage[\"(reassigned)\"][j],usedLabelName,usedLabelType)}else if(isUnstackingFunctionOuter&&(state.funct[\"(isCapturing)\"]=!0),subScope)if(subScope[\"(usages)\"][usedLabelName]){var subScopeUsage=subScope[\"(usages)\"][usedLabelName];subScopeUsage[\"(modified)\"]=subScopeUsage[\"(modified)\"].concat(usage[\"(modified)\"]),subScopeUsage[\"(tokens)\"]=subScopeUsage[\"(tokens)\"].concat(usage[\"(tokens)\"]),subScopeUsage[\"(reassigned)\"]=subScopeUsage[\"(reassigned)\"].concat(usage[\"(reassigned)\"]),subScopeUsage[\"(onlyUsedSubFunction)\"]=!1}else subScope[\"(usages)\"][usedLabelName]=usage,isUnstackingFunctionBody&&(subScope[\"(usages)\"][usedLabelName][\"(onlyUsedSubFunction)\"]=!0);else if(\"boolean\"==typeof _current[\"(predefined)\"][usedLabelName]){if(delete declared[usedLabelName],usedPredefinedAndGlobals[usedLabelName]=marker,_current[\"(predefined)\"][usedLabelName]===!1&&usage[\"(reassigned)\"])for(j=0;usage[\"(reassigned)\"].length>j;j++)warning(\"W020\",usage[\"(reassigned)\"][j])}else if(usage[\"(tokens)\"])for(j=0;usage[\"(tokens)\"].length>j;j++){var undefinedToken=usage[\"(tokens)\"][j];undefinedToken.forgiveUndef||(state.option.undef&&!undefinedToken.ignoreUndef&&warning(\"W117\",undefinedToken,usedLabelName),impliedGlobals[usedLabelName]?impliedGlobals[usedLabelName].line.push(undefinedToken.line):impliedGlobals[usedLabelName]={name:usedLabelName,line:[undefinedToken.line]})}}if(subScope||Object.keys(declared).forEach(function(labelNotUsed){_warnUnused(labelNotUsed,declared[labelNotUsed],\"var\")}),subScope&&!isUnstackingFunctionBody&&!isUnstackingFunctionParams&&!isUnstackingFunctionOuter){var labelNames=Object.keys(currentLabels);for(i=0;labelNames.length>i;i++){var defLabelName=labelNames[i];currentLabels[defLabelName][\"(blockscoped)\"]||\"exception\"===currentLabels[defLabelName][\"(type)\"]||this.funct.has(defLabelName,{excludeCurrent:!0})||(subScope[\"(labels)\"][defLabelName]=currentLabels[defLabelName],\"global\"!==_currentFunctBody[\"(type)\"]&&(subScope[\"(labels)\"][defLabelName][\"(useOutsideOfScope)\"]=!0),delete currentLabels[defLabelName])}}_checkForUnused(),_scopeStack.pop(),isUnstackingFunctionBody&&(_currentFunctBody=_scopeStack[_.findLastIndex(_scopeStack,function(scope){return scope[\"(isFuncBody)\"]||\"global\"===scope[\"(type)\"]})]),_current=subScope},addParam:function(labelName,token,type){if(type=type||\"param\",\"exception\"===type){var previouslyDefinedLabelType=this.funct.labeltype(labelName);previouslyDefinedLabelType&&\"exception\"!==previouslyDefinedLabelType&&(state.option.node||warning(\"W002\",state.tokens.next,labelName))}if(_.has(_current[\"(labels)\"],labelName)?_current[\"(labels)\"][labelName].duplicated=!0:(_checkOuterShadow(labelName,token,type),_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":token,\"(unused)\":!0},_current[\"(params)\"].push(labelName)),_.has(_current[\"(usages)\"],labelName)){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}},validateParams:function(){if(\"global\"!==_currentFunctBody[\"(type)\"]){var isStrict=state.isStrict(),currentFunctParamScope=_currentFunctBody[\"(parent)\"];currentFunctParamScope[\"(params)\"]&&currentFunctParamScope[\"(params)\"].forEach(function(labelName){var label=currentFunctParamScope[\"(labels)\"][labelName];label&&label.duplicated&&(isStrict?warning(\"E011\",label[\"(token)\"],labelName):state.option.shadow!==!0&&warning(\"W004\",label[\"(token)\"],labelName))})}},getUsedOrDefinedGlobals:function(){var list=Object.keys(usedPredefinedAndGlobals);return usedPredefinedAndGlobals.__proto__===marker&&-1===list.indexOf(\"__proto__\")&&list.push(\"__proto__\"),list},getImpliedGlobals:function(){var values=_.values(impliedGlobals),hasProto=!1;return impliedGlobals.__proto__&&(hasProto=values.some(function(value){return\"__proto__\"===value.name}),hasProto||values.push(impliedGlobals.__proto__)),values},getUnuseds:function(){return unuseds},has:function(labelName){return Boolean(_getLabel(labelName))},labeltype:function(labelName){var scopeLabels=_getLabel(labelName);return scopeLabels?scopeLabels[labelName][\"(type)\"]:null},addExported:function(labelName){var globalLabels=_scopeStack[0][\"(labels)\"];if(_.has(declared,labelName))delete declared[labelName];else if(_.has(globalLabels,labelName))globalLabels[labelName][\"(unused)\"]=!1;else{for(var i=1;_scopeStack.length>i;i++){var scope=_scopeStack[i];if(scope[\"(type)\"])break;if(_.has(scope[\"(labels)\"],labelName)&&!scope[\"(labels)\"][labelName][\"(blockscoped)\"])return scope[\"(labels)\"][labelName][\"(unused)\"]=!1,void 0}exported[labelName]=!0}},setExported:function(labelName,token){this.block.use(labelName,token)\n},addlabel:function(labelName,opts){var type=opts.type,token=opts.token,isblockscoped=\"let\"===type||\"const\"===type||\"class\"===type,isexported=\"global\"===(isblockscoped?_current:_currentFunctBody)[\"(type)\"]&&_.has(exported,labelName);if(_checkOuterShadow(labelName,token,type),isblockscoped){var declaredInCurrentScope=_current[\"(labels)\"][labelName];if(declaredInCurrentScope||_current!==_currentFunctBody||\"global\"===_current[\"(type)\"]||(declaredInCurrentScope=!!_currentFunctBody[\"(parent)\"][\"(labels)\"][labelName]),!declaredInCurrentScope&&_current[\"(usages)\"][labelName]){var usage=_current[\"(usages)\"][labelName];usage[\"(onlyUsedSubFunction)\"]?_latedefWarning(type,labelName,token):warning(\"E056\",token,labelName,type)}declaredInCurrentScope?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&scopeManagerInst.funct.has(labelName)&&warning(\"W004\",token,labelName),scopeManagerInst.block.add(labelName,type,token,!isexported)}else{var declaredInCurrentFunctionScope=scopeManagerInst.funct.has(labelName);!declaredInCurrentFunctionScope&&usedSoFarInCurrentFunction(labelName)&&_latedefWarning(type,labelName,token),scopeManagerInst.funct.has(labelName,{onlyBlockscoped:!0})?warning(\"E011\",token,labelName):state.option.shadow!==!0&&declaredInCurrentFunctionScope&&\"__proto__\"!==labelName&&\"global\"!==_currentFunctBody[\"(type)\"]&&warning(\"W004\",token,labelName),scopeManagerInst.funct.add(labelName,type,token,!isexported),\"global\"===_currentFunctBody[\"(type)\"]&&(usedPredefinedAndGlobals[labelName]=marker)}},funct:{labeltype:function(labelName,options){for(var onlyBlockscoped=options&&options.onlyBlockscoped,excludeParams=options&&options.excludeParams,currentScopeIndex=_scopeStack.length-(options&&options.excludeCurrent?2:1),i=currentScopeIndex;i>=0;i--){var current=_scopeStack[i];if(current[\"(labels)\"][labelName]&&(!onlyBlockscoped||current[\"(labels)\"][labelName][\"(blockscoped)\"]))return current[\"(labels)\"][labelName][\"(type)\"];var scopeCheck=excludeParams?_scopeStack[i-1]:current;if(scopeCheck&&\"functionparams\"===scopeCheck[\"(type)\"])return null}return null},hasBreakLabel:function(labelName){for(var i=_scopeStack.length-1;i>=0;i--){var current=_scopeStack[i];if(current[\"(breakLabels)\"][labelName])return!0;if(\"functionparams\"===current[\"(type)\"])return!1}return!1},has:function(labelName,options){return Boolean(this.labeltype(labelName,options))},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!1,\"(function)\":_currentFunctBody,\"(unused)\":unused}}},block:{isGlobal:function(){return\"global\"===_current[\"(type)\"]},use:function(labelName,token){var paramScope=_currentFunctBody[\"(parent)\"];paramScope&&paramScope[\"(labels)\"][labelName]&&\"param\"===paramScope[\"(labels)\"][labelName][\"(type)\"]&&(scopeManagerInst.funct.has(labelName,{excludeParams:!0,onlyBlockscoped:!0})||(paramScope[\"(labels)\"][labelName][\"(unused)\"]=!1)),token&&(state.ignored.W117||state.option.undef===!1)&&(token.ignoreUndef=!0),_setupUsages(labelName),token&&(token[\"(function)\"]=_currentFunctBody,_current[\"(usages)\"][labelName][\"(tokens)\"].push(token))},reassign:function(labelName,token){this.modify(labelName,token),_current[\"(usages)\"][labelName][\"(reassigned)\"].push(token)},modify:function(labelName,token){_setupUsages(labelName),_current[\"(usages)\"][labelName][\"(modified)\"].push(token)},add:function(labelName,type,tok,unused){_current[\"(labels)\"][labelName]={\"(type)\":type,\"(token)\":tok,\"(blockscoped)\":!0,\"(unused)\":unused}},addBreakLabel:function(labelName,opts){var token=opts.token;scopeManagerInst.funct.hasBreakLabel(labelName)?warning(\"E011\",token,labelName):\"outer\"===state.option.shadow&&(scopeManagerInst.funct.has(labelName)?warning(\"W004\",token,labelName):_checkOuterShadow(labelName,token)),_current[\"(breakLabels)\"][labelName]=token}}};return scopeManagerInst};module.exports=scopeManager},{\"../lodash\":\"/node_modules/jshint/lodash.js\",events:\"/node_modules/browserify/node_modules/events/events.js\"}],\"/node_modules/jshint/src/state.js\":[function(_dereq_,module,exports){\"use strict\";var NameStack=_dereq_(\"./name-stack.js\"),state={syntax:{},isStrict:function(){return this.directive[\"use strict\"]||this.inClassBody||this.option.module||\"implied\"===this.option.strict},inMoz:function(){return this.option.moz},inES6:function(){return this.option.moz||this.option.esversion>=6},inES5:function(strict){return strict?!(this.option.esversion&&5!==this.option.esversion||this.option.moz):!this.option.esversion||this.option.esversion>=5||this.option.moz},reset:function(){this.tokens={prev:null,next:null,curr:null},this.option={},this.funct=null,this.ignored={},this.directive={},this.jsonMode=!1,this.jsonWarnings=[],this.lines=[],this.tab=\"\",this.cache={},this.ignoredLines={},this.forinifcheckneeded=!1,this.nameStack=new NameStack,this.inClassBody=!1}};exports.state=state},{\"./name-stack.js\":\"/node_modules/jshint/src/name-stack.js\"}],\"/node_modules/jshint/src/style.js\":[function(_dereq_,module,exports){\"use strict\";exports.register=function(linter){linter.on(\"Identifier\",function(data){linter.getOption(\"proto\")||\"__proto__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name,\"6\"]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"iterator\")||\"__iterator__\"===data.name&&linter.warn(\"W103\",{line:data.line,\"char\":data.char,data:[data.name]})}),linter.on(\"Identifier\",function(data){linter.getOption(\"camelcase\")&&data.name.replace(/^_+|_+$/g,\"\").indexOf(\"_\")>-1&&!data.name.match(/^[A-Z0-9_]*$/)&&linter.warn(\"W106\",{line:data.line,\"char\":data.from,data:[data.name]})}),linter.on(\"String\",function(data){var code,quotmark=linter.getOption(\"quotmark\");quotmark&&(\"single\"===quotmark&&\"'\"!==data.quote&&(code=\"W109\"),\"double\"===quotmark&&'\"'!==data.quote&&(code=\"W108\"),quotmark===!0&&(linter.getCache(\"quotmark\")||linter.setCache(\"quotmark\",data.quote),linter.getCache(\"quotmark\")!==data.quote&&(code=\"W110\")),code&&linter.warn(code,{line:data.line,\"char\":data.char}))}),linter.on(\"Number\",function(data){\".\"===data.value.charAt(0)&&linter.warn(\"W008\",{line:data.line,\"char\":data.char,data:[data.value]}),\".\"===data.value.substr(data.value.length-1)&&linter.warn(\"W047\",{line:data.line,\"char\":data.char,data:[data.value]}),/^00+/.test(data.value)&&linter.warn(\"W046\",{line:data.line,\"char\":data.char,data:[data.value]})}),linter.on(\"String\",function(data){var re=/^(?:javascript|jscript|ecmascript|vbscript|livescript)\\s*:/i;linter.getOption(\"scripturl\")||re.test(data.value)&&linter.warn(\"W107\",{line:data.line,\"char\":data.char})})}},{}],\"/node_modules/jshint/src/vars.js\":[function(_dereq_,module,exports){\"use strict\";exports.reservedVars={arguments:!1,NaN:!1},exports.ecmaIdentifiers={3:{Array:!1,Boolean:!1,Date:!1,decodeURI:!1,decodeURIComponent:!1,encodeURI:!1,encodeURIComponent:!1,Error:!1,eval:!1,EvalError:!1,Function:!1,hasOwnProperty:!1,isFinite:!1,isNaN:!1,Math:!1,Number:!1,Object:!1,parseInt:!1,parseFloat:!1,RangeError:!1,ReferenceError:!1,RegExp:!1,String:!1,SyntaxError:!1,TypeError:!1,URIError:!1},5:{JSON:!1},6:{Map:!1,Promise:!1,Proxy:!1,Reflect:!1,Set:!1,Symbol:!1,WeakMap:!1,WeakSet:!1}},exports.browser={Audio:!1,Blob:!1,addEventListener:!1,applicationCache:!1,atob:!1,blur:!1,btoa:!1,cancelAnimationFrame:!1,CanvasGradient:!1,CanvasPattern:!1,CanvasRenderingContext2D:!1,CSS:!1,clearInterval:!1,clearTimeout:!1,close:!1,closed:!1,Comment:!1,CustomEvent:!1,DOMParser:!1,defaultStatus:!1,Document:!1,document:!1,DocumentFragment:!1,Element:!1,ElementTimeControl:!1,Event:!1,event:!1,fetch:!1,FileReader:!1,FormData:!1,focus:!1,frames:!1,getComputedStyle:!1,HTMLElement:!1,HTMLAnchorElement:!1,HTMLBaseElement:!1,HTMLBlockquoteElement:!1,HTMLBodyElement:!1,HTMLBRElement:!1,HTMLButtonElement:!1,HTMLCanvasElement:!1,HTMLCollection:!1,HTMLDirectoryElement:!1,HTMLDivElement:!1,HTMLDListElement:!1,HTMLFieldSetElement:!1,HTMLFontElement:!1,HTMLFormElement:!1,HTMLFrameElement:!1,HTMLFrameSetElement:!1,HTMLHeadElement:!1,HTMLHeadingElement:!1,HTMLHRElement:!1,HTMLHtmlElement:!1,HTMLIFrameElement:!1,HTMLImageElement:!1,HTMLInputElement:!1,HTMLIsIndexElement:!1,HTMLLabelElement:!1,HTMLLayerElement:!1,HTMLLegendElement:!1,HTMLLIElement:!1,HTMLLinkElement:!1,HTMLMapElement:!1,HTMLMenuElement:!1,HTMLMetaElement:!1,HTMLModElement:!1,HTMLObjectElement:!1,HTMLOListElement:!1,HTMLOptGroupElement:!1,HTMLOptionElement:!1,HTMLParagraphElement:!1,HTMLParamElement:!1,HTMLPreElement:!1,HTMLQuoteElement:!1,HTMLScriptElement:!1,HTMLSelectElement:!1,HTMLStyleElement:!1,HTMLTableCaptionElement:!1,HTMLTableCellElement:!1,HTMLTableColElement:!1,HTMLTableElement:!1,HTMLTableRowElement:!1,HTMLTableSectionElement:!1,HTMLTemplateElement:!1,HTMLTextAreaElement:!1,HTMLTitleElement:!1,HTMLUListElement:!1,HTMLVideoElement:!1,history:!1,Image:!1,Intl:!1,length:!1,localStorage:!1,location:!1,matchMedia:!1,MessageChannel:!1,MessageEvent:!1,MessagePort:!1,MouseEvent:!1,moveBy:!1,moveTo:!1,MutationObserver:!1,name:!1,Node:!1,NodeFilter:!1,NodeList:!1,Notification:!1,navigator:!1,onbeforeunload:!0,onblur:!0,onerror:!0,onfocus:!0,onload:!0,onresize:!0,onunload:!0,open:!1,openDatabase:!1,opener:!1,Option:!1,parent:!1,performance:!1,print:!1,Range:!1,requestAnimationFrame:!1,removeEventListener:!1,resizeBy:!1,resizeTo:!1,screen:!1,scroll:!1,scrollBy:!1,scrollTo:!1,sessionStorage:!1,setInterval:!1,setTimeout:!1,SharedWorker:!1,status:!1,SVGAElement:!1,SVGAltGlyphDefElement:!1,SVGAltGlyphElement:!1,SVGAltGlyphItemElement:!1,SVGAngle:!1,SVGAnimateColorElement:!1,SVGAnimateElement:!1,SVGAnimateMotionElement:!1,SVGAnimateTransformElement:!1,SVGAnimatedAngle:!1,SVGAnimatedBoolean:!1,SVGAnimatedEnumeration:!1,SVGAnimatedInteger:!1,SVGAnimatedLength:!1,SVGAnimatedLengthList:!1,SVGAnimatedNumber:!1,SVGAnimatedNumberList:!1,SVGAnimatedPathData:!1,SVGAnimatedPoints:!1,SVGAnimatedPreserveAspectRatio:!1,SVGAnimatedRect:!1,SVGAnimatedString:!1,SVGAnimatedTransformList:!1,SVGAnimationElement:!1,SVGCSSRule:!1,SVGCircleElement:!1,SVGClipPathElement:!1,SVGColor:!1,SVGColorProfileElement:!1,SVGColorProfileRule:!1,SVGComponentTransferFunctionElement:!1,SVGCursorElement:!1,SVGDefsElement:!1,SVGDescElement:!1,SVGDocument:!1,SVGElement:!1,SVGElementInstance:!1,SVGElementInstanceList:!1,SVGEllipseElement:!1,SVGExternalResourcesRequired:!1,SVGFEBlendElement:!1,SVGFEColorMatrixElement:!1,SVGFEComponentTransferElement:!1,SVGFECompositeElement:!1,SVGFEConvolveMatrixElement:!1,SVGFEDiffuseLightingElement:!1,SVGFEDisplacementMapElement:!1,SVGFEDistantLightElement:!1,SVGFEFloodElement:!1,SVGFEFuncAElement:!1,SVGFEFuncBElement:!1,SVGFEFuncGElement:!1,SVGFEFuncRElement:!1,SVGFEGaussianBlurElement:!1,SVGFEImageElement:!1,SVGFEMergeElement:!1,SVGFEMergeNodeElement:!1,SVGFEMorphologyElement:!1,SVGFEOffsetElement:!1,SVGFEPointLightElement:!1,SVGFESpecularLightingElement:!1,SVGFESpotLightElement:!1,SVGFETileElement:!1,SVGFETurbulenceElement:!1,SVGFilterElement:!1,SVGFilterPrimitiveStandardAttributes:!1,SVGFitToViewBox:!1,SVGFontElement:!1,SVGFontFaceElement:!1,SVGFontFaceFormatElement:!1,SVGFontFaceNameElement:!1,SVGFontFaceSrcElement:!1,SVGFontFaceUriElement:!1,SVGForeignObjectElement:!1,SVGGElement:!1,SVGGlyphElement:!1,SVGGlyphRefElement:!1,SVGGradientElement:!1,SVGHKernElement:!1,SVGICCColor:!1,SVGImageElement:!1,SVGLangSpace:!1,SVGLength:!1,SVGLengthList:!1,SVGLineElement:!1,SVGLinearGradientElement:!1,SVGLocatable:!1,SVGMPathElement:!1,SVGMarkerElement:!1,SVGMaskElement:!1,SVGMatrix:!1,SVGMetadataElement:!1,SVGMissingGlyphElement:!1,SVGNumber:!1,SVGNumberList:!1,SVGPaint:!1,SVGPathElement:!1,SVGPathSeg:!1,SVGPathSegArcAbs:!1,SVGPathSegArcRel:!1,SVGPathSegClosePath:!1,SVGPathSegCurvetoCubicAbs:!1,SVGPathSegCurvetoCubicRel:!1,SVGPathSegCurvetoCubicSmoothAbs:!1,SVGPathSegCurvetoCubicSmoothRel:!1,SVGPathSegCurvetoQuadraticAbs:!1,SVGPathSegCurvetoQuadraticRel:!1,SVGPathSegCurvetoQuadraticSmoothAbs:!1,SVGPathSegCurvetoQuadraticSmoothRel:!1,SVGPathSegLinetoAbs:!1,SVGPathSegLinetoHorizontalAbs:!1,SVGPathSegLinetoHorizontalRel:!1,SVGPathSegLinetoRel:!1,SVGPathSegLinetoVerticalAbs:!1,SVGPathSegLinetoVerticalRel:!1,SVGPathSegList:!1,SVGPathSegMovetoAbs:!1,SVGPathSegMovetoRel:!1,SVGPatternElement:!1,SVGPoint:!1,SVGPointList:!1,SVGPolygonElement:!1,SVGPolylineElement:!1,SVGPreserveAspectRatio:!1,SVGRadialGradientElement:!1,SVGRect:!1,SVGRectElement:!1,SVGRenderingIntent:!1,SVGSVGElement:!1,SVGScriptElement:!1,SVGSetElement:!1,SVGStopElement:!1,SVGStringList:!1,SVGStylable:!1,SVGStyleElement:!1,SVGSwitchElement:!1,SVGSymbolElement:!1,SVGTRefElement:!1,SVGTSpanElement:!1,SVGTests:!1,SVGTextContentElement:!1,SVGTextElement:!1,SVGTextPathElement:!1,SVGTextPositioningElement:!1,SVGTitleElement:!1,SVGTransform:!1,SVGTransformList:!1,SVGTransformable:!1,SVGURIReference:!1,SVGUnitTypes:!1,SVGUseElement:!1,SVGVKernElement:!1,SVGViewElement:!1,SVGViewSpec:!1,SVGZoomAndPan:!1,Text:!1,TextDecoder:!1,TextEncoder:!1,TimeEvent:!1,top:!1,URL:!1,WebGLActiveInfo:!1,WebGLBuffer:!1,WebGLContextEvent:!1,WebGLFramebuffer:!1,WebGLProgram:!1,WebGLRenderbuffer:!1,WebGLRenderingContext:!1,WebGLShader:!1,WebGLShaderPrecisionFormat:!1,WebGLTexture:!1,WebGLUniformLocation:!1,WebSocket:!1,window:!1,Window:!1,Worker:!1,XDomainRequest:!1,XMLHttpRequest:!1,XMLSerializer:!1,XPathEvaluator:!1,XPathException:!1,XPathExpression:!1,XPathNamespace:!1,XPathNSResolver:!1,XPathResult:!1},exports.devel={alert:!1,confirm:!1,console:!1,Debug:!1,opera:!1,prompt:!1},exports.worker={importScripts:!0,postMessage:!0,self:!0,FileReaderSync:!0},exports.nonstandard={escape:!1,unescape:!1},exports.couch={require:!1,respond:!1,getRow:!1,emit:!1,send:!1,start:!1,sum:!1,log:!1,exports:!1,module:!1,provides:!1},exports.node={__filename:!1,__dirname:!1,GLOBAL:!1,global:!1,module:!1,acequire:!1,Buffer:!0,console:!0,exports:!0,process:!0,setTimeout:!0,clearTimeout:!0,setInterval:!0,clearInterval:!0,setImmediate:!0,clearImmediate:!0},exports.browserify={__filename:!1,__dirname:!1,global:!1,module:!1,acequire:!1,Buffer:!0,exports:!0,process:!0},exports.phantom={phantom:!0,acequire:!0,WebPage:!0,console:!0,exports:!0},exports.qunit={asyncTest:!1,deepEqual:!1,equal:!1,expect:!1,module:!1,notDeepEqual:!1,notEqual:!1,notPropEqual:!1,notStrictEqual:!1,ok:!1,propEqual:!1,QUnit:!1,raises:!1,start:!1,stop:!1,strictEqual:!1,test:!1,\"throws\":!1},exports.rhino={defineClass:!1,deserialize:!1,gc:!1,help:!1,importClass:!1,importPackage:!1,java:!1,load:!1,loadClass:!1,Packages:!1,print:!1,quit:!1,readFile:!1,readUrl:!1,runCommand:!1,seal:!1,serialize:!1,spawn:!1,sync:!1,toint32:!1,version:!1},exports.shelljs={target:!1,echo:!1,exit:!1,cd:!1,pwd:!1,ls:!1,find:!1,cp:!1,rm:!1,mv:!1,mkdir:!1,test:!1,cat:!1,sed:!1,grep:!1,which:!1,dirs:!1,pushd:!1,popd:!1,env:!1,exec:!1,chmod:!1,config:!1,error:!1,tempdir:!1},exports.typed={ArrayBuffer:!1,ArrayBufferView:!1,DataView:!1,Float32Array:!1,Float64Array:!1,Int16Array:!1,Int32Array:!1,Int8Array:!1,Uint16Array:!1,Uint32Array:!1,Uint8Array:!1,Uint8ClampedArray:!1},exports.wsh={ActiveXObject:!0,Enumerator:!0,GetObject:!0,ScriptEngine:!0,ScriptEngineBuildVersion:!0,ScriptEngineMajorVersion:!0,ScriptEngineMinorVersion:!0,VBArray:!0,WSH:!0,WScript:!0,XDomainRequest:!0},exports.dojo={dojo:!1,dijit:!1,dojox:!1,define:!1,require:!1},exports.jquery={$:!1,jQuery:!1},exports.mootools={$:!1,$$:!1,Asset:!1,Browser:!1,Chain:!1,Class:!1,Color:!1,Cookie:!1,Core:!1,Document:!1,DomReady:!1,DOMEvent:!1,DOMReady:!1,Drag:!1,Element:!1,Elements:!1,Event:!1,Events:!1,Fx:!1,Group:!1,Hash:!1,HtmlTable:!1,IFrame:!1,IframeShim:!1,InputValidator:!1,instanceOf:!1,Keyboard:!1,Locale:!1,Mask:!1,MooTools:!1,Native:!1,Options:!1,OverText:!1,Request:!1,Scroller:!1,Slick:!1,Slider:!1,Sortables:!1,Spinner:!1,Swiff:!1,Tips:!1,Type:!1,typeOf:!1,URI:!1,Window:!1},exports.prototypejs={$:!1,$$:!1,$A:!1,$F:!1,$H:!1,$R:!1,$break:!1,$continue:!1,$w:!1,Abstract:!1,Ajax:!1,Class:!1,Enumerable:!1,Element:!1,Event:!1,Field:!1,Form:!1,Hash:!1,Insertion:!1,ObjectRange:!1,PeriodicalExecuter:!1,Position:!1,Prototype:!1,Selector:!1,Template:!1,Toggle:!1,Try:!1,Autocompleter:!1,Builder:!1,Control:!1,Draggable:!1,Draggables:!1,Droppables:!1,Effect:!1,Sortable:!1,SortableObserver:!1,Sound:!1,Scriptaculous:!1},exports.yui={YUI:!1,Y:!1,YUI_config:!1},exports.mocha={mocha:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,context:!1,xcontext:!1,before:!1,after:!1,beforeEach:!1,afterEach:!1,suite:!1,test:!1,setup:!1,teardown:!1,suiteSetup:!1,suiteTeardown:!1},exports.jasmine={jasmine:!1,describe:!1,xdescribe:!1,it:!1,xit:!1,beforeEach:!1,afterEach:!1,setFixtures:!1,loadFixtures:!1,spyOn:!1,expect:!1,runs:!1,waitsFor:!1,waits:!1,beforeAll:!1,afterAll:!1,fail:!1,fdescribe:!1,fit:!1,pending:!1}},{}]},{},[\"/node_modules/jshint/src/jshint.js\"])}),ace.define(\"ace/mode/javascript_worker\",[\"require\",\"exports\",\"module\",\"ace/lib/oop\",\"ace/worker/mirror\",\"ace/mode/javascript/jshint\"],function(acequire,exports,module){\"use strict\";function startRegex(arr){return RegExp(\"^(\"+arr.join(\"|\")+\")\")}var oop=acequire(\"../lib/oop\"),Mirror=acequire(\"../worker/mirror\").Mirror,lint=acequire(\"./javascript/jshint\").JSHINT,disabledWarningsRe=startRegex([\"Bad for in variable '(.+)'.\",'Missing \"use strict\"']),errorsRe=startRegex([\"Unexpected\",\"Expected \",\"Confusing (plus|minus)\",\"\\\\{a\\\\} unterminated regular expression\",\"Unclosed \",\"Unmatched \",\"Unbegun comment\",\"Bad invocation\",\"Missing space after\",\"Missing operator at\"]),infoRe=startRegex([\"Expected an assignment\",\"Bad escapement of EOL\",\"Unexpected comma\",\"Unexpected space\",\"Missing radix parameter.\",\"A leading decimal point can\",\"\\\\['{a}'\\\\] is better written in dot notation.\",\"'{a}' used out of scope\"]),JavaScriptWorker=exports.JavaScriptWorker=function(sender){Mirror.call(this,sender),this.setTimeout(500),this.setOptions()};oop.inherits(JavaScriptWorker,Mirror),function(){this.setOptions=function(options){this.options=options||{esnext:!0,moz:!0,devel:!0,browser:!0,node:!0,laxcomma:!0,laxbreak:!0,lastsemic:!0,onevar:!1,passfail:!1,maxerr:100,expr:!0,multistr:!0,globalstrict:!0},this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.changeOptions=function(newOptions){oop.mixin(this.options,newOptions),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.isValidJS=function(str){try{eval(\"throw 0;\"+str)}catch(e){if(0===e)return!0}return!1},this.onUpdate=function(){var value=this.doc.getValue();if(value=value.replace(/^#!.*\\n/,\"\\n\"),!value)return this.sender.emit(\"annotate\",[]);var errors=[],maxErrorLevel=this.isValidJS(value)?\"warning\":\"error\";lint(value,this.options,this.options.globals);for(var results=lint.errors,errorAdded=!1,i=0;results.length>i;i++){var error=results[i];if(error){var raw=error.raw,type=\"warning\";if(\"Missing semicolon.\"==raw){var str=error.evidence.substr(error.character);str=str.charAt(str.search(/\\S/)),\"error\"==maxErrorLevel&&str&&/[\\w\\d{(['\"]/.test(str)?(error.reason='Missing \";\" before statement',type=\"error\"):type=\"info\"}else{if(disabledWarningsRe.test(raw))continue;infoRe.test(raw)?type=\"info\":errorsRe.test(raw)?(errorAdded=!0,type=maxErrorLevel):\"'{a}' is not defined.\"==raw?type=\"warning\":\"'{a}' is defined but never used.\"==raw&&(type=\"info\")}errors.push({row:error.line-1,column:error.character-1,text:error.reason,type:type,raw:raw})}}this.sender.emit(\"annotate\",errors)}}.call(JavaScriptWorker.prototype)}),ace.define(\"ace/lib/es5-shim\",[\"require\",\"exports\",\"module\"],function(){function Empty(){}function doesDefinePropertyWork(object){try{return Object.defineProperty(object,\"sentinel\",{}),\"sentinel\"in object}catch(exception){}}function toInteger(n){return n=+n,n!==n?n=0:0!==n&&n!==1/0&&n!==-(1/0)&&(n=(n>0||-1)*Math.floor(Math.abs(n))),n}Function.prototype.bind||(Function.prototype.bind=function(that){var target=this;if(\"function\"!=typeof target)throw new TypeError(\"Function.prototype.bind called on incompatible \"+target);var args=slice.call(arguments,1),bound=function(){if(this instanceof bound){var result=target.apply(this,args.concat(slice.call(arguments)));return Object(result)===result?result:this}return target.apply(that,args.concat(slice.call(arguments)))};return target.prototype&&(Empty.prototype=target.prototype,bound.prototype=new Empty,Empty.prototype=null),bound});var defineGetter,defineSetter,lookupGetter,lookupSetter,supportsAccessors,call=Function.prototype.call,prototypeOfArray=Array.prototype,prototypeOfObject=Object.prototype,slice=prototypeOfArray.slice,_toString=call.bind(prototypeOfObject.toString),owns=call.bind(prototypeOfObject.hasOwnProperty);if((supportsAccessors=owns(prototypeOfObject,\"__defineGetter__\"))&&(defineGetter=call.bind(prototypeOfObject.__defineGetter__),defineSetter=call.bind(prototypeOfObject.__defineSetter__),lookupGetter=call.bind(prototypeOfObject.__lookupGetter__),lookupSetter=call.bind(prototypeOfObject.__lookupSetter__)),2!=[1,2].splice(0).length)if(function(){function makeArray(l){var a=Array(l+2);return a[0]=a[1]=0,a}var lengthBefore,array=[];return array.splice.apply(array,makeArray(20)),array.splice.apply(array,makeArray(26)),lengthBefore=array.length,array.splice(5,0,\"XXX\"),lengthBefore+1==array.length,lengthBefore+1==array.length?!0:void 0}()){var array_splice=Array.prototype.splice;Array.prototype.splice=function(start,deleteCount){return arguments.length?array_splice.apply(this,[void 0===start?0:start,void 0===deleteCount?this.length-start:deleteCount].concat(slice.call(arguments,2))):[]}}else Array.prototype.splice=function(pos,removeCount){var length=this.length;pos>0?pos>length&&(pos=length):void 0==pos?pos=0:0>pos&&(pos=Math.max(length+pos,0)),length>pos+removeCount||(removeCount=length-pos);var removed=this.slice(pos,pos+removeCount),insert=slice.call(arguments,2),add=insert.length;if(pos===length)add&&this.push.apply(this,insert);else{var remove=Math.min(removeCount,length-pos),tailOldPos=pos+remove,tailNewPos=tailOldPos+add-remove,tailCount=length-tailOldPos,lengthAfterRemove=length-remove;if(tailOldPos>tailNewPos)for(var i=0;tailCount>i;++i)this[tailNewPos+i]=this[tailOldPos+i];else if(tailNewPos>tailOldPos)for(i=tailCount;i--;)this[tailNewPos+i]=this[tailOldPos+i];if(add&&pos===lengthAfterRemove)this.length=lengthAfterRemove,this.push.apply(this,insert);else for(this.length=lengthAfterRemove+add,i=0;add>i;++i)this[pos+i]=insert[i]}return removed};Array.isArray||(Array.isArray=function(obj){return\"[object Array]\"==_toString(obj)});var boxedString=Object(\"a\"),splitString=\"a\"!=boxedString[0]||!(0 in boxedString);if(Array.prototype.forEach||(Array.prototype.forEach=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError;for(;length>++i;)i in self&&fun.call(thisp,self[i],i,object)}),Array.prototype.map||(Array.prototype.map=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=Array(length),thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(result[i]=fun.call(thisp,self[i],i,object));return result}),Array.prototype.filter||(Array.prototype.filter=function(fun){var value,object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,result=[],thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)i in self&&(value=self[i],fun.call(thisp,value,i,object)&&result.push(value));return result}),Array.prototype.every||(Array.prototype.every=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&!fun.call(thisp,self[i],i,object))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0,thisp=arguments[1];if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");for(var i=0;length>i;i++)if(i in self&&fun.call(thisp,self[i],i,object))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduce of empty array with no initial value\");var result,i=0;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i++];break}if(++i>=length)throw new TypeError(\"reduce of empty array with no initial value\")}for(;length>i;i++)i in self&&(result=fun.call(void 0,result,self[i],i,object));return result}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(fun){var object=toObject(this),self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):object,length=self.length>>>0;if(\"[object Function]\"!=_toString(fun))throw new TypeError(fun+\" is not a function\");if(!length&&1==arguments.length)throw new TypeError(\"reduceRight of empty array with no initial value\");var result,i=length-1;if(arguments.length>=2)result=arguments[1];else for(;;){if(i in self){result=self[i--];break}if(0>--i)throw new TypeError(\"reduceRight of empty array with no initial value\")}do i in this&&(result=fun.call(void 0,result,self[i],i,object));while(i--);return result}),Array.prototype.indexOf&&-1==[0,1].indexOf(1,2)||(Array.prototype.indexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=0;for(arguments.length>1&&(i=toInteger(arguments[1])),i=i>=0?i:Math.max(0,length+i);length>i;i++)if(i in self&&self[i]===sought)return i;return-1}),Array.prototype.lastIndexOf&&-1==[0,1].lastIndexOf(0,-3)||(Array.prototype.lastIndexOf=function(sought){var self=splitString&&\"[object String]\"==_toString(this)?this.split(\"\"):toObject(this),length=self.length>>>0;if(!length)return-1;var i=length-1;for(arguments.length>1&&(i=Math.min(i,toInteger(arguments[1]))),i=i>=0?i:length-Math.abs(i);i>=0;i--)if(i in self&&sought===self[i])return i;return-1}),Object.getPrototypeOf||(Object.getPrototypeOf=function(object){return object.__proto__||(object.constructor?object.constructor.prototype:prototypeOfObject)}),!Object.getOwnPropertyDescriptor){var ERR_NON_OBJECT=\"Object.getOwnPropertyDescriptor called on a non-object: \";Object.getOwnPropertyDescriptor=function(object,property){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT+object);if(owns(object,property)){var descriptor,getter,setter;if(descriptor={enumerable:!0,configurable:!0},supportsAccessors){var prototype=object.__proto__;object.__proto__=prototypeOfObject;var getter=lookupGetter(object,property),setter=lookupSetter(object,property);if(object.__proto__=prototype,getter||setter)return getter&&(descriptor.get=getter),setter&&(descriptor.set=setter),descriptor}return descriptor.value=object[property],descriptor}}}if(Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(object){return Object.keys(object)}),!Object.create){var createEmpty;createEmpty=null===Object.prototype.__proto__?function(){return{__proto__:null}}:function(){var empty={};for(var i in empty)empty[i]=null;return empty.constructor=empty.hasOwnProperty=empty.propertyIsEnumerable=empty.isPrototypeOf=empty.toLocaleString=empty.toString=empty.valueOf=empty.__proto__=null,empty},Object.create=function(prototype,properties){var object;if(null===prototype)object=createEmpty();else{if(\"object\"!=typeof prototype)throw new TypeError(\"typeof prototype[\"+typeof prototype+\"] != 'object'\");var Type=function(){};Type.prototype=prototype,object=new Type,object.__proto__=prototype}return void 0!==properties&&Object.defineProperties(object,properties),object}}if(Object.defineProperty){var definePropertyWorksOnObject=doesDefinePropertyWork({}),definePropertyWorksOnDom=\"undefined\"==typeof document||doesDefinePropertyWork(document.createElement(\"div\"));if(!definePropertyWorksOnObject||!definePropertyWorksOnDom)var definePropertyFallback=Object.defineProperty}if(!Object.defineProperty||definePropertyFallback){var ERR_NON_OBJECT_DESCRIPTOR=\"Property description must be an object: \",ERR_NON_OBJECT_TARGET=\"Object.defineProperty called on non-object: \",ERR_ACCESSORS_NOT_SUPPORTED=\"getters & setters can not be defined on this javascript engine\";Object.defineProperty=function(object,property,descriptor){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(ERR_NON_OBJECT_TARGET+object);if(\"object\"!=typeof descriptor&&\"function\"!=typeof descriptor||null===descriptor)throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR+descriptor);if(definePropertyFallback)try{return definePropertyFallback.call(Object,object,property,descriptor)}catch(exception){}if(owns(descriptor,\"value\"))if(supportsAccessors&&(lookupGetter(object,property)||lookupSetter(object,property))){var prototype=object.__proto__;object.__proto__=prototypeOfObject,delete object[property],object[property]=descriptor.value,object.__proto__=prototype}else object[property]=descriptor.value;else{if(!supportsAccessors)throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);owns(descriptor,\"get\")&&defineGetter(object,property,descriptor.get),owns(descriptor,\"set\")&&defineSetter(object,property,descriptor.set)}return object}}Object.defineProperties||(Object.defineProperties=function(object,properties){for(var property in properties)owns(properties,property)&&Object.defineProperty(object,property,properties[property]);return object}),Object.seal||(Object.seal=function(object){return object}),Object.freeze||(Object.freeze=function(object){return object});try{Object.freeze(function(){})}catch(exception){Object.freeze=function(freezeObject){return function(object){return\"function\"==typeof object?object:freezeObject(object)}}(Object.freeze)}if(Object.preventExtensions||(Object.preventExtensions=function(object){return object}),Object.isSealed||(Object.isSealed=function(){return!1}),Object.isFrozen||(Object.isFrozen=function(){return!1}),Object.isExtensible||(Object.isExtensible=function(object){if(Object(object)===object)throw new TypeError;for(var name=\"\";owns(object,name);)name+=\"?\";object[name]=!0;var returnValue=owns(object,name);return delete object[name],returnValue}),!Object.keys){var hasDontEnumBug=!0,dontEnums=[\"toString\",\"toLocaleString\",\"valueOf\",\"hasOwnProperty\",\"isPrototypeOf\",\"propertyIsEnumerable\",\"constructor\"],dontEnumsLength=dontEnums.length;for(var key in{toString:null})hasDontEnumBug=!1;Object.keys=function(object){if(\"object\"!=typeof object&&\"function\"!=typeof object||null===object)throw new TypeError(\"Object.keys called on a non-object\");var keys=[];for(var name in object)owns(object,name)&&keys.push(name);if(hasDontEnumBug)for(var i=0,ii=dontEnumsLength;ii>i;i++){var dontEnum=dontEnums[i];owns(object,dontEnum)&&keys.push(dontEnum)}return keys}}Date.now||(Date.now=function(){return(new Date).getTime()});var ws=\"\t\\n\u000b\\f\\r    \\u2028\\u2029\";if(!String.prototype.trim||ws.trim()){ws=\"[\"+ws+\"]\";var trimBeginRegexp=RegExp(\"^\"+ws+ws+\"*\"),trimEndRegexp=RegExp(ws+ws+\"*$\");String.prototype.trim=function(){return(this+\"\").replace(trimBeginRegexp,\"\").replace(trimEndRegexp,\"\")}}var toObject=function(o){if(null==o)throw new TypeError(\"can't convert \"+o+\" to object\");return Object(o)}});";
/***/ }),
/* 49 */
/***/ (function(module, exports) {
ace.define("ace/theme/terminal",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-terminal-theme";
exports.cssText = ".ace-terminal-theme .ace_gutter {\
background: #1a0005;\
color: steelblue\
}\
.ace-terminal-theme .ace_print-margin {\
width: 1px;\
background: #1a1a1a\
}\
.ace-terminal-theme {\
background-color: black;\
color: #DEDEDE\
}\
.ace-terminal-theme .ace_cursor {\
color: #9F9F9F\
}\
.ace-terminal-theme .ace_marker-layer .ace_selection {\
background: #424242\
}\
.ace-terminal-theme.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px black;\
}\
.ace-terminal-theme .ace_marker-layer .ace_step {\
background: rgb(0, 0, 0)\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket {\
background: #090;\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket-start {\
background: #090;\
}\
.ace-terminal-theme .ace_marker-layer .ace_bracket-unmatched {\
margin: -1px 0 0 -1px;\
border: 1px solid #900\
}\
.ace-terminal-theme .ace_marker-layer .ace_active-line {\
background: #2A2A2A\
}\
.ace-terminal-theme .ace_gutter-active-line {\
background-color: #2A112A\
}\
.ace-terminal-theme .ace_marker-layer .ace_selected-word {\
border: 1px solid #424242\
}\
.ace-terminal-theme .ace_invisible {\
color: #343434\
}\
.ace-terminal-theme .ace_keyword,\
.ace-terminal-theme .ace_meta,\
.ace-terminal-theme .ace_storage,\
.ace-terminal-theme .ace_storage.ace_type,\
.ace-terminal-theme .ace_support.ace_type {\
color: tomato\
}\
.ace-terminal-theme .ace_keyword.ace_operator {\
color: deeppink\
}\
.ace-terminal-theme .ace_constant.ace_character,\
.ace-terminal-theme .ace_constant.ace_language,\
.ace-terminal-theme .ace_constant.ace_numeric,\
.ace-terminal-theme .ace_keyword.ace_other.ace_unit,\
.ace-terminal-theme .ace_support.ace_constant,\
.ace-terminal-theme .ace_variable.ace_parameter {\
color: #E78C45\
}\
.ace-terminal-theme .ace_constant.ace_other {\
color: gold\
}\
.ace-terminal-theme .ace_invalid {\
color: yellow;\
background-color: red\
}\
.ace-terminal-theme .ace_invalid.ace_deprecated {\
color: #CED2CF;\
background-color: #B798BF\
}\
.ace-terminal-theme .ace_fold {\
background-color: #7AA6DA;\
border-color: #DEDEDE\
}\
.ace-terminal-theme .ace_entity.ace_name.ace_function,\
.ace-terminal-theme .ace_support.ace_function,\
.ace-terminal-theme .ace_variable {\
color: #7AA6DA\
}\
.ace-terminal-theme .ace_support.ace_class,\
.ace-terminal-theme .ace_support.ace_type {\
color: #E7C547\
}\
.ace-terminal-theme .ace_heading,\
.ace-terminal-theme .ace_string {\
color: #B9CA4A\
}\
.ace-terminal-theme .ace_entity.ace_name.ace_tag,\
.ace-terminal-theme .ace_entity.ace_other.ace_attribute-name,\
.ace-terminal-theme .ace_meta.ace_tag,\
.ace-terminal-theme .ace_string.ace_regexp,\
.ace-terminal-theme .ace_variable {\
color: #D54E53\
}\
.ace-terminal-theme .ace_comment {\
color: orangered\
}\
.ace-terminal-theme .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLBWV/8PAAK4AYnhiq+xAAAAAElFTkSuQmCC) right repeat-y;\
}\
";
var dom = acequire("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
/***/ }),
/* 50 */
/***/ (function(module, exports) {
ace.define("ace/theme/twilight",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-twilight";
exports.cssText = ".ace-twilight .ace_gutter {\
background: #232323;\
color: #E2E2E2\
}\
.ace-twilight .ace_print-margin {\
width: 1px;\
background: #232323\
}\
.ace-twilight {\
background-color: #141414;\
color: #F8F8F8\
}\
.ace-twilight .ace_cursor {\
color: #A7A7A7\
}\
.ace-twilight .ace_marker-layer .ace_selection {\
background: rgba(221, 240, 255, 0.20)\
}\
.ace-twilight.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px #141414;\
}\
.ace-twilight .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0)\
}\
.ace-twilight .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(255, 255, 255, 0.25)\
}\
.ace-twilight .ace_marker-layer .ace_active-line {\
background: rgba(255, 255, 255, 0.031)\
}\
.ace-twilight .ace_gutter-active-line {\
background-color: rgba(255, 255, 255, 0.031)\
}\
.ace-twilight .ace_marker-layer .ace_selected-word {\
border: 1px solid rgba(221, 240, 255, 0.20)\
}\
.ace-twilight .ace_invisible {\
color: rgba(255, 255, 255, 0.25)\
}\
.ace-twilight .ace_keyword,\
.ace-twilight .ace_meta {\
color: #CDA869\
}\
.ace-twilight .ace_constant,\
.ace-twilight .ace_constant.ace_character,\
.ace-twilight .ace_constant.ace_character.ace_escape,\
.ace-twilight .ace_constant.ace_other,\
.ace-twilight .ace_heading,\
.ace-twilight .ace_markup.ace_heading,\
.ace-twilight .ace_support.ace_constant {\
color: #CF6A4C\
}\
.ace-twilight .ace_invalid.ace_illegal {\
color: #F8F8F8;\
background-color: rgba(86, 45, 86, 0.75)\
}\
.ace-twilight .ace_invalid.ace_deprecated {\
text-decoration: underline;\
font-style: italic;\
color: #D2A8A1\
}\
.ace-twilight .ace_support {\
color: #9B859D\
}\
.ace-twilight .ace_fold {\
background-color: #AC885B;\
border-color: #F8F8F8\
}\
.ace-twilight .ace_support.ace_function {\
color: #DAD085\
}\
.ace-twilight .ace_list,\
.ace-twilight .ace_markup.ace_list,\
.ace-twilight .ace_storage {\
color: #F9EE98\
}\
.ace-twilight .ace_entity.ace_name.ace_function,\
.ace-twilight .ace_meta.ace_tag,\
.ace-twilight .ace_variable {\
color: #AC885B\
}\
.ace-twilight .ace_string {\
color: #8F9D6A\
}\
.ace-twilight .ace_string.ace_regexp {\
color: #E9C062\
}\
.ace-twilight .ace_comment {\
font-style: italic;\
color: #5F5A60\
}\
.ace-twilight .ace_variable {\
color: #7587A6\
}\
.ace-twilight .ace_xml-pe {\
color: #494949\
}\
.ace-twilight .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWMQERFpYLC1tf0PAAgOAnPnhxyiAAAAAElFTkSuQmCC) right repeat-y\
}";
var dom = acequire("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
/***/ }),
/* 51 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return beginInfiltration; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_InfiltrationBox_js__ = __webpack_require__(52);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* 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;
}
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;
}
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(__WEBPACK_IMPORTED_MODULE_5__utils_InfiltrationBox_js__["a" /* infiltrationBoxCreate */])(inst);
}
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-kill");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-knockout");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-stealthknockout");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-assassinate");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-hacksecurity");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-destroysecurity");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-sneak");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-pickdoor");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-bribe");
Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-escape");
__WEBPACK_IMPORTED_MODULE_1__engine_js__["Engine"].loadWorldContent();
}
function nextInfiltrationLevel(inst) {
++inst.clearanceLevel;
updateInfiltrationLevelText(inst);
//Buttons
var killButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-kill");
var knockoutButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-knockout");
var stealthKnockoutButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-stealthknockout");
var assassinateButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-assassinate");
var hackSecurityButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-hacksecurity");
var destroySecurityButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-destroysecurity");
var sneakButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-sneak");
var pickdoorButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-pickdoor");
var bribeButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-bribe");
var escapeButton = Object(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["b" /* 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(__WEBPACK_IMPORTED_MODULE_4__utils_HelperFunctions_js__["d" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].karma -= 1;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(1.5 * inst.securityLevel / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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!");
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].karma -= 3;
++__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].numPeopleKilled;
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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!");
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].karma -= 3;
++__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
endInfiltrationLevel(inst);
return false;
} else {
var dmgTaken = Math.max(1, Math.round(inst.securityLevel / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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 / __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
}
updateInfiltrationButtons(inst, scenario);
updateInfiltrationLevelText(inst);
return false;
});
bribeButton.addEventListener("click", function() {
var bribeAmt = __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].InfiltrationBribeBaseAmount * inst.clearanceLevel;
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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);
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])((res[1]*100)-100, 2).toString() + "%");
if (__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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 + ".<br>" +
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 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].faction_rep_mult * 1.25;
var secretMoneyValue = baseSecretValue * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue;
inst.secretsStolen.push(baseSecretValue);
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You found and stole a set of classified documents from the company. " +
"These classified secrets could probably be sold for money ($" +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(secretMoneyValue, 2) + "), or they " +
"could be given to factions for reputation (" + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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 + "<br>");
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];
totalMoneyValue += inst.secretsStolen[i] * __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue;
}
document.getElementById("infiltration-level-text").innerHTML =
"Facility name: " + inst.companyName + "<br>" +
"Clearance Level: " + inst.clearanceLevel + "<br>" +
"Security Level: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.securityLevel, 3) + "<br><br>" +
"Total reputation value of secrets stolen: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalValue, 3) + "<br>" +
"Total monetary value of secrets stolen: $" + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(totalMoneyValue, 2) + "<br><br>" +
"Hack exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + "<br>" +
"Str exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + "<br>" +
"Def exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + "<br>" +
"Dex exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + "<br>" +
"Agi exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + "<br>" +
"Cha exp gained: " + Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 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" +
"<span class='tooltiptext'>" +
"Attempt to escape the facility with the classified secrets and " +
"documents you have stolen. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(escapeChance*100, 2) + "% chance of success. If you fail, " +
"the security level will increase by 5%.</span>";
switch(scenario) {
case InfiltrationScenarios.TechOrLockedDoor:
document.getElementById("infiltration-pickdoor").innerHTML = "Lockpick" +
"<span class='tooltiptext'>" +
"Attempt to pick the locked door. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%.</span>";
case InfiltrationScenarios.TechOnly:
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack" +
"<span class='tooltiptext'>" +
"Attempt to hack and disable the security system. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%.</span>";
document.getElementById("infiltration-destroysecurity").innerHTML = "Destroy security" +
"<span class='tooltiptext'>" +
"Attempt to violently destroy the security system. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security system. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
break;
case InfiltrationScenarios.Bots:
document.getElementById("infiltration-kill").innerHTML = "Destroy bots" +
"<span class='tooltiptext'>" +
"Attempt to destroy the security bots through combat. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%. </span>";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate bots" +
"<span class='tooltiptext'>" +
"Attempt to stealthily destroy the security bots through assassination. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. </span>";
document.getElementById("infiltration-hacksecurity").innerHTML = "Hack bots" +
"<span class='tooltiptext'>" +
"Attempt to disable the security bots by hacking them. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(hackChance*100, 2) + "% chance of success. " +
"If you succeed, the security level will increase by 1%. If you fail, " +
"the security level will increase by 5%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security bots. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
break;
case InfiltrationScenarios.Guards:
default:
document.getElementById("infiltration-kill").innerHTML = "Kill" +
"<span class='tooltiptext'>" +
"Attempt to kill the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%. </span>";
document.getElementById("infiltration-knockout").innerHTML = "Knockout" +
"<span class='tooltiptext'>" +
"Attempt to knockout the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* 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%. </span>";
document.getElementById("infiltration-stealthknockout").innerHTML = "Stealth Knockout" +
"<span class='tooltiptext'>" +
"Attempt to stealthily knockout the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(stealthKnockoutChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 10%. </span>";
document.getElementById("infiltration-assassinate").innerHTML = "Assassinate" +
"<span class='tooltiptext'>" +
"Attempt to assassinate the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(assassinateChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 5%. </span>";
document.getElementById("infiltration-sneak").innerHTML = "Sneak" +
"<span class='tooltiptext'>" +
"Attempt to sneak past the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(sneakChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 8%. </span>";
document.getElementById("infiltration-bribe").innerHTML = "Bribe" +
"<span class='tooltiptext'>" +
"Attempt to bribe the security guard. You have a " +
Object(__WEBPACK_IMPORTED_MODULE_6__utils_StringHelperFunctions_js__["c" /* formatNumber */])(bribeChance*100, 2) + "% chance of success. " +
"If you fail, the security level will increase by 15%. </span>";
break;
}
}
//Kill
//Success: 5%, Failure 10%, -Karma
function attemptInfiltrationKill(inst) {
var chance = getInfiltrationKillChance(inst);
inst.gainStrengthExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility) / (1.5 * lvl));
}
//Knockout
//Success: 3%, Failure: 10%
function attemptInfiltrationKnockout(inst) {
var chance = getInfiltrationKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility) / (1.75 * lvl));
}
//Stealth knockout
//Success: 0%, Failure: 10%
function attemptInfiltrationStealthKnockout(inst) {
var chance = getInfiltrationStealthKnockoutChance(inst);
inst.gainStrengthExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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.5 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength +
2 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity +
2 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility) / (3 * lvl));
}
//Assassination
//Success: 0%, Failure: 5%, -Karma
function attemptInfiltrationAssassinate(inst) {
var chance = getInfiltrationAssassinateChance(inst);
inst.gainStrengthExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity +
0.5 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility) / (2 * lvl));
}
//Destroy security
//Success: 5%, Failure: 10%
function attemptInfiltrationDestroySecurity(inst) {
var chance = getInfiltrationDestroySecurityChance(inst);
inst.gainStrengthExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength_exp_mult;
inst.gainDefenseExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].defense_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity_exp_mult;
inst.gainAgilityExp(inst.securityLevel / 100) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].strength +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility) / (2 * lvl));
}
//Hack security
//Success: 1%, Failure: 5%
function attemptInfiltrationHack(inst) {
var chance = getInfiltrationHackChance(inst);
inst.gainHackingExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_exp_mult;
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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].hacking_skill) / lvl);
}
//Sneak past security
//Success: 0%, Failure: 8%
function attemptInfiltrationSneak(inst) {
var chance = getInfiltrationSneakChance(inst);
inst.gainAgilityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility +
0.5 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity) / (2 * lvl));
}
//Pick locked door
//Success: 1%, Failure: 3%
function attemptInfiltrationPickLockedDoor(inst) {
var chance = getInfiltrationPickLockedDoorChance(inst);
inst.gainDexterityExp(inst.securityLevel / 75) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity) / lvl);
}
//Bribe
//Success: 0%, Failure: 15%,
function attemptInfiltrationBribe(inst) {
var chance = getInfiltrationBribeChance(inst);
inst.gainCharismaExp(inst.securityLevel / 50) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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,
(__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].charisma) / lvl);
}
//Escape
//Failure: 5%
function attemptInfiltrationEscape(inst) {
var chance = getInfiltrationEscapeChance(inst);
inst.gainAgilityExp(inst.securityLevel / 50) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility_exp_mult;
inst.gainDexterityExp(inst.securityLevel / 50) * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* 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 * __WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].agility +
__WEBPACK_IMPORTED_MODULE_2__Player_js__["a" /* Player */].dexterity) / lvl);
}
/***/ }),
/* 52 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return infiltrationBoxCreate; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__ = __webpack_require__(5);
/* InfiltrationBox.js */
function infiltrationBoxClose() {
var box = document.getElementById("infiltration-box-container");
box.style.display = "none";
}
function infiltrationBoxOpen() {
var box = document.getElementById("infiltration-box-container");
box.style.display = "block";
}
function infiltrationSetText(txt) {
var textBox = document.getElementById("infiltration-box-text");
textBox.innerHTML = txt;
}
//ram argument is in GB
function infiltrationBoxCreate(inst) {
var totalValue = 0;
for (var i = 0; i < inst.secretsStolen.length; ++i) {
totalValue += inst.secretsStolen[i];
}
if (totalValue == 0) {
Object(__WEBPACK_IMPORTED_MODULE_3__DialogBox_js__["a" /* dialogBoxCreate */])("You successfully escaped the facility but you did not steal " +
"anything of worth when infiltrating.<br><br>" +
"You gained:<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp<br>");
return;
}
var facValue = totalValue * __WEBPACK_IMPORTED_MODULE_2__src_Player_js__["a" /* Player */].faction_rep_mult * 1.2
var moneyValue = totalValue * __WEBPACK_IMPORTED_MODULE_0__src_Constants_js__["a" /* CONSTANTS */].InfiltrationMoneyValue;
infiltrationSetText("You can sell the classified documents and secrets " +
"you stole from " + inst.companyName + " for $" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(moneyValue, 2) + " on the black market or you can give it " +
"to a faction to gain " + Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(facValue, 3) + " reputation with " +
"that faction.");
var selector = document.getElementById("infiltration-faction-select");
selector.innerHTML = "";
for (var i = 0; i < __WEBPACK_IMPORTED_MODULE_2__src_Player_js__["a" /* Player */].factions.length; ++i) {
selector.innerHTML += "<option value='" + __WEBPACK_IMPORTED_MODULE_2__src_Player_js__["a" /* Player */].factions[i] +
"'>" + __WEBPACK_IMPORTED_MODULE_2__src_Player_js__["a" /* Player */].factions[i] + "</option>";
}
var sellButton = Object(__WEBPACK_IMPORTED_MODULE_4__HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-box-sell");
setTimeout(function() {
sellButton.addEventListener("click", function() {
__WEBPACK_IMPORTED_MODULE_2__src_Player_js__["a" /* Player */].gainMoney(moneyValue);
Object(__WEBPACK_IMPORTED_MODULE_3__DialogBox_js__["a" /* dialogBoxCreate */])("You sold the classified information you stole from " + inst.companyName +
" for $" + moneyValue + " on the black market!<br><br>" +
"You gained:<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp<br>");
infiltrationBoxClose();
return false;
});
}, 750);
var factionButton = Object(__WEBPACK_IMPORTED_MODULE_4__HelperFunctions_js__["b" /* clearEventListeners */])("infiltration-box-faction");
setTimeout(function() {
factionButton.addEventListener("click", function() {
var facName = selector.options[selector.selectedIndex].value;
var faction = __WEBPACK_IMPORTED_MODULE_1__src_Faction_js__["b" /* Factions */][facName];
if (faction == null) {
Object(__WEBPACK_IMPORTED_MODULE_3__DialogBox_js__["a" /* dialogBoxCreate */])("Error finding faction. This is a bug please report to developer");
return false;
}
faction.playerReputation += facValue;
Object(__WEBPACK_IMPORTED_MODULE_3__DialogBox_js__["a" /* dialogBoxCreate */])("You gave the classified information you stole from " + inst.companyName +
" to " + facName + " and gained " + Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(facValue, 3) + " reputation with the faction. <br><br>" +
"You gained:<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.hackingExpGained, 3) + " hacking exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.strExpGained, 3) + " str exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.defExpGained, 3) + " def exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.dexExpGained, 3) + " dex exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.agiExpGained, 3) + " agi exp<br>" +
Object(__WEBPACK_IMPORTED_MODULE_5__StringHelperFunctions_js__["c" /* formatNumber */])(inst.chaExpGained, 3) + " cha exp<br>");
infiltrationBoxClose();
return false;
});
}, 750);
infiltrationBoxOpen();
}
/***/ }),
/* 53 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FactionInfo; });
//Contains the "information" property for all the Factions, which is just a description
//of each faction
let FactionInfo = {
//Endgame
IlluminatiInfo: "Humanity never changes. No matter how civilized society becomes, it will eventually fall back " +
"into chaos. And from this chaos, we are the Invisible hand that guides them to order. ",
DaedalusInfo: "Yesterday we obeyed kings and bent our necks to emperors. Today we kneel only to truth.",
CovenantInfo: "Surrender yourself. Give up your empty individuality to become part of something great, something eternal. " +
"Become a slave. Submit your mind, body, and soul. Only then can you set yourself free.<br><br> " +
"Only then can you discover immortality.",
//Megacorporations, each forms its own faction
ECorpInfo: "ECorp's mission is simple: to connect the world of today with the technology of tomorrow. " +
"With our wide range of Internet-related software and commercial hardware, ECorp makes the world's " +
"information universally accessible.",
MegaCorpInfo: "MegaCorp does things that others don't. We imagine. We create. We invent. We build things that " +
"others have never even dreamed of. Our work fills the world's needs for food, water, power, and " +
"transporation on an unprecendented scale, in ways that no other company can.<br><br>" +
"In our labs and factories and on the ground with customers, MegaCorp is ushering in a new era for the world.",
BachmanAndAssociatesInfo: "Where Law and Business meet - thats where we are. <br><br>" +
"Legal Insight - Business Instinct - Experience Innovation",
BladeIndustriesInfo: "Augmentation is salvation",
NWOInfo: "The human being created civilization not because of willingness but of a need to be assimilated into higher orders of structure and meaning.",
ClarkeIncorporatedInfo: "Unlocking the power of the genome",
OmniTekIncorporatedInfo: "Simply put, our mission is to design and build robots that make a difference",
FourSigmaInfo: "The scientific method is the best way to approach investing. Big strategies backed up with big data. Driven by " +
"deep learning and innovative ideas. And improved by iteration. That's Four Sigma.",
KuaiGongInternationalInfo: "Dream big. Work hard. Make history.",
//Other Corporations
FulcrumSecretTechnologiesInfo: "TODO",
//Hacker groups
BitRunnersInfo: "Our entire lives are controlled by bits. All of our actions, our thoughts, our personal information. "+
"It's all transformed into bits, stored in bits, communicated through bits. Its 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.<br><br>" +
"Those who run the bits, run the world",
BlackHandInfo: "The world, so afraid of strong government, now has no government. Only power - Digital power. Financial power. " +
"Technological power. " +
"And those at the top rule with an invisible hand. They built a society where the rich get richer, " +
"and everyone else suffers.<br><br>" +
"So much pain. So many lives. Their darkness must end.",
NiteSecInfo:
" __..__ <br>" +
" _.nITESECNIt. <br>" +
" .-'NITESECNITESEc. <br>" +
" .' NITESECNITESECn <br>" +
" / NITESECNITESEC; <br>" +
" : :NITESECNITESEC; <br>" +
" ; $ NITESECNITESECN <br>" +
" : _, ,N'ITESECNITESEC <br>" +
" : .+^^`, : `NITESECNIT <br>" +
" ) /), `-,-=,NITESECNI <br>" +
" / ^ ,-;|NITESECN; <br>" +
" / _.' '-';NITESECN <br>" +
" ( , ,-''`^NITE' <br>" +
" )` :`. .' <br>" +
" )-- ; `- / <br>" +
" \' _.-' : <br>" +
" ( _.-' \. \ <br>" +
" \------. \ \ <br>" +
" \. \ \ <br>" +
" \ _.nIt <br>" +
" \ _.nITESECNi <br>" +
" nITESECNIT^' \ <br>" +
" NITE^' ___ \ <br>" +
" / .gP''''Tp. \ <br>" +
" : d' . `b \ <br>" +
" ; d' o `b ; <br>" +
" / d; `b| <br>" +
" /, $; @ `: <br>" +
" /' $$ ; <br>" +
" .' $$b o | <br>" +
" .' d$$$; : <br>" +
" / .d$$$$; , ; <br>" +
" d .dNITESEC $ | <br>" +
" :bp.__.gNITESEC$$ :$ ; <br>" +
" NITESECNITESECNIT $$b : <br>",
//City factions, essentially governments
ChongqingInfo: "Serve the people",
Sector12Info: "The City of the Future",
HongKongInfo: "Asia's World City",
AevumInfo: "The Silicon City",
IshimaInfo: "The East Asian Order of the Future",
VolhavenInfo: "Benefit, Honour, and Glory",
//Criminal Organizations/Gangs
SpeakersForTheDeadInfo: "It is better to reign in hell than to serve in heaven.",
DarkArmyInfo: "The World doesn't care about right or wrong. It's all about power.",
TheSyndicateInfo: "Honor holds you back",
SilhouetteInfo: "Corporations have filled the void of power left behind by the collapse of Western government. The issue is they've become so big " +
"that you don't know who they're working for. And if you're employed at one of these corporations, you don't even know who you're working " +
"for. <br><br>" +
"That's terror. Terror, fear, and corruption. All born into the system, all propagated by the system.",
TetradsInfo: "Following the Mandate of Heaven and Carrying out the Way",
SlumSnakesInfo: "Slum Snakes rule!",
//Earlygame factions - factions the player will prestige with early on that don't
//belong in other categories
NetburnersInfo: "~~//*>H4CK|\|3T 8URN3R5**>?>\\~~",
TianDiHuiInfo: "Obey Heaven and Work Righteousness",
CyberSecInfo: "The Internet is the first thing that humanity has built that humanity doesnt 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.",
}
/***/ }),
/* 54 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return factionInvitationBoxCreate; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__ = __webpack_require__(1);
/* Faction Invitation Pop-up box */
function factionInvitationBoxClose() {
var factionInvitationBox = document.getElementById("faction-invitation-box-container");
factionInvitationBox.style.display = "none";
}
function factionInvitationBoxOpen() {
var factionInvitationBox = document.getElementById("faction-invitation-box-container");
factionInvitationBox.style.display = "block";
}
function factionInvitationSetText(txt) {
var textBox = document.getElementById("faction-invitation-box-text");
textBox.innerHTML = txt;
}
function factionInvitationSetMessage(msg) {
var msgBox = document.getElementById("faction-invitation-box-message");
msgBox.innerHTML = msg;
}
//ram argument is in GB
function factionInvitationBoxCreate(faction) {
factionInvitationSetText("You have received a faction invitation from " + faction.name);
//TODO Faction invitation message
var newYesButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-yes");
newYesButton.addEventListener("click", function() {
Object(__WEBPACK_IMPORTED_MODULE_0__src_Faction_js__["h" /* joinFaction */])(faction);
factionInvitationBoxClose();
return false;
});
var noButton = Object(__WEBPACK_IMPORTED_MODULE_2__HelperFunctions_js__["b" /* clearEventListeners */])("faction-invitation-box-no");
noButton.addEventListener("click", function() {
factionInvitationBoxClose();
faction.alreadyInvited = true;
__WEBPACK_IMPORTED_MODULE_1__src_Player_js__["a" /* Player */].factionInvitations.push(faction.name);
return false;
});
factionInvitationBoxOpen();
}
/***/ }),
/* 55 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return purchaseServer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return purchaseRamForHomeComputer; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__utils_YesNoBox_js__ = __webpack_require__(20);
/* Functions to handle any server-related purchasing:
* Purchasing new servers
* Purchasing more RAM for home computer
*/
function purchaseServer(ram, cost) {
//Check if player has enough money
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) {
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You don't have enough money to purchase this server!");
return;
}
//Maximum server limit
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.length >= __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit) {
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You have reached the maximum limit of " + __WEBPACK_IMPORTED_MODULE_0__Constants_js__["a" /* CONSTANTS */].PurchasedServerLimit + " servers. " +
"You cannot purchase any more. You can " +
"delete some of your purchased servers using the deleteServer() Netscript function in a script");
return;
}
var hostname = Object(__WEBPACK_IMPORTED_MODULE_4__utils_YesNoBox_js__["h" /* yesNoTxtInpBoxGetInput */])();
if (hostname == "") {
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You must enter a hostname for your new server!");
return;
}
//Create server
var newServ = new Server(createRandomIp(), hostname, "", false, true, true, ram);
AddToAllServers(newServ);
//Add to Player's purchasedServers array
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].purchasedServers.push(newServ.ip);
//Connect new server to home computer
var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer();
homeComputer.serversOnNetwork.push(newServ.ip);
newServ.serversOnNetwork.push(homeComputer.ip);
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost);
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Server successfully purchased with hostname " + hostname);
}
function purchaseRamForHomeComputer(cost) {
if (__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].money.lt(cost)) {
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("You do not have enough money to purchase additional RAM for your home computer");
return;
}
var homeComputer = __WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].getHomeComputer();
homeComputer.maxRam *= 2;
__WEBPACK_IMPORTED_MODULE_1__Player_js__["a" /* Player */].loseMoney(cost);
Object(__WEBPACK_IMPORTED_MODULE_3__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Purchased additional RAM for home computer! It now has " + homeComputer.maxRam + "GB of RAM.");
}
/***/ }),
/* 56 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TerminalHelpText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HelpTexts; });
/* HelpText.js */
let TerminalHelpText =
"Type 'help name' to learn more about the command 'name'<br><br>" +
'alias [-g] [name="value"] Create or display Terminal aliases<br>' +
"analyze Get information about the current machine <br>" +
"buy [-l/program] Purchase a program through the Dark Web<br>" +
"cat [file] Display a .msg or .lit file<br>" +
"check [script] [args...] Print a script's logs to Terminal<br>" +
"clear Clear all text on the terminal <br>" +
"cls See 'clear' command <br>" +
"connect [ip/hostname] Connects to a remote server<br>" +
"free Check the machine's memory (RAM) usage<br>" +
"hack Hack the current machine<br>" +
"help [command] Display this help text, or the help text for a command<br>" +
"home Connect to home computer<br>" +
"hostname Displays the hostname of the machine<br>" +
"ifconfig Displays the IP address of the machine<br>" +
"kill [script] [args...] Stops the specified script on the current server <br>" +
"killall Stops all running scripts on the current machine<br>" +
"ls [| grep pattern] Displays all files on the machine<br>" +
"mem [script] [-t] [n] Displays the amount of RAM required to run the script<br>" +
"nano [script] Script editor - Open up and edit a script<br>" +
"ps Display all scripts that are currently running<br>" +
"rm [file] Delete a file from the server<br>" +
"run [name] [-t] [n] [args...] Execute a program or script<br>" +
"scan Prints all immediately-available network connections<br>" +
"scan-analyze [d] Prints info for all servers up to <i>d</i> nodes away<br>" +
"scp [file] [server] Copies a script or .lit file to a destination server<br>" +
"sudov Shows whether you have root access on this computer<br>" +
"tail [script] [args...] Displays dynamic logs for the specified script<br>" +
"theme [preset] | bg txt hlgt Change the color scheme of the UI<br>" +
"top Displays all running scripts and their RAM usage<br>" +
'unalias "[alias name]" Deletes the specified alias<br>';
let HelpTexts = {
alias: 'alias [-g] [name="value"] <br>' +
"Create or display aliases. An alias enables a replacement of a word with another string. " +
"It can be used to abbreviate a commonly used command, or commonly used parts of a command. The NAME " +
"of an alias defines the word that will be replaced, while the VALUE defines what it will be replaced by. For example, " +
"you could create the alias 'nuke' for the Terminal command 'run NUKE.exe' using the following: <br><br>" +
'alias nuke="run NUKE.exe"<br><br>' +
"Then, to run the NUKE.exe program you would just have to enter 'nuke' in Terminal rather than the full command. " +
"It is important to note that 'default' aliases will only be substituted for the first word of a Terminal command. For " +
"example, if the following alias was set: <br><br>" +
'alias worm="HTTPWorm.exe"<br><br>' +
"and then you tried to run the following terminal command: <br><br>" +
"run worm<br><br>" +
"This would fail because the worm alias is not the first word of a Terminal command. To allow an alias to be substituted " +
"anywhere in a Terminal command, rather than just the first word, you must set it to be a global alias using the -g flag: <br><br>" +
'alias -g worm="HTTPWorm.exe"<br><br>' +
"Now, the 'worm' alias will be substituted anytime it shows up as an individual word in a Terminal command. <br><br>" +
"Entering just the command 'alias' without any arguments prints the list of all defined aliases in the reusable form " +
"'alias NAME=VALUE' on the Terminal. <br><br>" +
"The 'unalias' command can be used to remove aliases.<br><br>",
analyze: "analze<br>" +
"Prints details and statistics about the current server. The information that is printed includes basic " +
"server details such as the hostname, whether the player has root access, what ports are opened/closed, and also " +
"hacking-related information such as an estimated chance to successfully hack, an estimate of how much money is " +
"available on the server, etc.",
buy: "buy [-l / program]<br>" +
"Purchase a program through the Dark Web. Requires a TOR router to use.<br><br>" +
"If this command is ran with the '-l' flag, it will display a list of all programs that can be bought through the " +
"dark web to the Terminal, as well as their costs.<br><br>" +
"Otherwise, the name of the program must be passed in as a parameter. This is name is NOT case-sensitive.",
cat: "cat [file]<br>" +
"Display message files, which are files ending with the '.msg' extension, or a literature file, which " +
"are files ending with the '.lit' extension. Examples:<br><br>" +
"cat j1.msg<br>" +
"cat foo.lit",
check: "check [script name] [args...]<br>" +
"Print the logs of the script specified by the script name and arguments to the Terminal. Each argument must be separated by " +
"a space. Remember that a running script is uniquely " +
"identified both by its name and the arguments that are used to start it. So, if a script was ran with the following arguments: <br><br>" +
"run foo.script 1 2 foodnstuff<br><br>" +
"Then to run the 'check' command on this script you would have to pass the same arguments in: <br><br>" +
"check foo.script 1 2 foodnstuff",
clear: "clear<br>" +
"Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " +
"and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'cls' command",
cls: "cls<br>" +
"Clear the Terminal screen, deleting all of the text. Note that this does not delete the user's command history, so using the up " +
"and down arrow keys is still valid. Also note that this is permanent and there is no way to undo this. Synonymous with 'clear' command",
connect: "connect [hostname/ip]<br>" +
"Connect to a remote server. The hostname or IP address of the remote server must be given as the argument " +
"to this command. Note that only servers that are immediately adjacent to the current server in the network can be connected to. To " +
"see which servers can be connected to, use the 'scan' command.",
free: "free<br>" +
"Display's the memory usage on the current machine. Print the amount of RAM that is available on the current server as well as " +
"how much of it is being used.",
hack: "hack<br>" +
"Attempt to hack the current server. Requires root access in order to be run. See the wiki page for hacking mechanics<br>",
help: "help [command]<br>" +
"Display Terminal help information. Without arguments, 'help' prints a list of all valid Terminal commands and a brief " +
"description of their functionality. You can also pass the name of a Terminal command as an argument to 'help' to print " +
"more detailed information about the Terminal command. Examples: <br><br>" +
"help alias<br>" +
"help scan-analyze",
home: "home<br>" +
"Connect to your home computer. This will work no matter what server you are currently connected to.",
hostname: "hostname<br>" +
"Prints the hostname of the current server",
ifconfig: "ipconfig<br>" +
"Prints the IP address of the current server",
kill: "kill [script name] [args...]<br>" +
"Kill the script specified by the script name and arguments. Each argument must be separated by " +
"a space. Remember that a running script is uniquely identified by " +
"both its name and the arguments that are used to start it. So, if a script was ran with the following arguments:<br><br>" +
"run foo.script 1 sigma-cosmetics<br><br>" +
"Then to kill this script the same arguments would have to be used:<br><br>" +
"kill foo.script 1 sigma-cosmetics<br><br>" +
"Note that after issuing the 'kill' command for a script, it may take a while for the script to actually stop running. " +
"This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " +
"The script will not be stopped/killed until after that time has elapsed.",
killall: "killall<br>" +
"Kills all scripts on the current server. " +
"Note that after the 'kill' command is issued for a script, it may take a while for the script to actually stop running. " +
"This will happen if the script is in the middle of a command such as grow() or weaken() that takes time to execute. " +
"The script will not be stopped/killed until after that time has elapsed.",
ls: "ls [| grep pattern]<br>" +
"The ls command, with no arguments, prints all files on the current server to the Terminal screen. " +
"This includes all scripts, programs, and message files. " +
"The files will be displayed in alphabetical order. <br><br>" +
"The '| grep pattern' optional parameter can be used to only display files whose filenames match the specified pattern. " +
"For example, if you wanted to only display files with the .script extension, you could use: <br><br>" +
"ls | grep .script<br><br>" +
"Alternatively, if you wanted to display all files with the word purchase in the filename, you could use: <br><br>" +
"ls | grep purchase",
mem: "mem [script name] [-t] [num threads]<br>" +
"Displays the amount of RAM needed to run the specified script with a single thread. The command can also be used to print " +
"the amount of RAM needed to run a script with multiple threads using the '-t' flag. If the '-t' flag is specified, then " +
"an argument for the number of threads must be passed in afterwards. Examples:<br><br>" +
"mem foo.script<br>" +
"mem foo.script -t 50<br>" +
"The first example above will print the amount of RAM needed to run 'foo.script' with a single thread. The second example " +
"above will print the amount of RAM needed to run 'foo.script' with 50 threads.",
nano: "nano [script name]<br>" +
"Opens up the specified script in the Script Editor. If the script does not already exist, then a new, empty script " +
"will be created",
ps: "ps<br>" +
"Prints all scripts that are running on the current server",
rm: "rm [file]<br>" +
"Removes the specified file from the current server. A file can be a script, a program, or a message file. <br><br>" +
"WARNING: This is permanent and cannot be undone",
run: "run [file name] [-t] [num threads] [args...]<br>" +
"Execute a program or a script.<br><br>" +
"The '[-t]', '[num threads]', and '[args...]' arguments are only valid when running a script. The '-t' flag is used " +
"to indicate that the script should be run with the specified number of threads. If the flag is omitted, " +
"then the script will be run with a single thread by default. " +
"If the '-t' flag is used, then it MUST come immediately " +
"after the script name, and the [num threads] argument MUST come immediately afterwards. <br><br>" +
"[args...] represents a variable number of arguments that will be passed into the script. See the documentation " +
"about script arguments. Each specified argument must be separated by a space. <br><br>",
scan: "scan<br>" +
"Prints all immediately-available network connection. This will print a list of all servers that you can currently connect " +
"to using the 'connect' Terminal command.",
"scan-analyze": "scan-analyze [depth]<br>" +
"Prints detailed information about all servers up to [depth] nodes away on the network. Calling " +
"'scan-analyze 1' will display information for the same servers that are shown by the 'scan' Terminal " +
"command. This command also shows the relative paths to reach each server.<br><br>" +
"By default, the maximum depth that can be specified for 'scan-analyze' is 3. However, once you have " +
"the DeepscanV1.exe and DeepscanV2.exe programs, you can execute 'scan-analyze' with a depth up to " +
"5 and 10, respectively.<br><br>" +
"The information 'scan-analyze' displays about each server includes whether or not you have root access to it, " +
"its required hacking level, the number of open ports required to run NUKE.exe on it, and how much RAM " +
"it has",
scp: "scp [filename] [target server]<br>" +
"Copies the specified file from the current server to the target server. " +
"This command only works for script files (.script extension) and literature files (.lit extension). " +
"The second argument passed in must be the hostname or IP of the target server.",
sudov: "sudov<br>" +
"Prints whether or not you have root access to the current machine",
tail: "tail [script name] [args...]<br>" +
"Displays dynamic logs for the script specified by the script name and arguments. Each argument must be separated " +
"by a space. Remember that a running script is uniquely identified by both its name and the arguments that were used " +
"to run it. So, if a script was ran with the following arguments: <br><br>" +
"run foo.script 10 50000<br><br>" +
"Then in order to check its logs with 'tail' the same arguments must be used: <br><br>" +
"tail foo.script 10 50000",
theme: "theme [preset] | [#background #text #highlight]<br>" +
"Change the color of the game's user interface<br><br>" +
"This command can be called with a preset theme. Currently, the supported presets are 'default', 'muted', and 'solarized'. " +
"However, you can also specify your own color scheme using hex values. To do so, you must specify three hex color values " +
"for the background color, the text color, and the highlight color. These hex values must be preceded by a pound sign (#) and " +
"must be either 3 or 6 digits. Example:<br><br>" +
"theme #ffffff #385 #235012<br><br>" +
"A color picker such as " +
"<a href='https://www.google.com/search?q=color+picker&oq=color+picker&aqs=chrome.0.0l6.951j0j1&sourceid=chrome&ie=UTF-8' target='_blank'>Google's</a> " +
"can be used to get your desired hex color values<br><br>" +
"Themes are not saved, so when the game is closed and then re-opened or reloaded then it will revert back to the default theme.",
top: "top<br>" +
"Prints a list of all scripts running on the current server as well as their thread count and how much " +
"RAM they are using in total.",
unalias: 'unalias "[alias name]"<br>' +
"Deletes the specified alias. Note that the double quotation marks are required. <br><br>" +
"As an example, if an alias was declared using:<br><br>" +
'alias r="run"<br><br>' +
"Then it could be removed using:<br><br>" +
'unalias "r"<br><br>' +
"It is not necessary to differentiate between global and non-global aliases when using 'unalias'",
}
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
/*
acorn.js
https://github.com/ternjs/acorn
Copyright (C) 2012-2017 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
(function (global, factory) {
true ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.acorn = global.acorn || {})));
}(this, (function (exports) { 'use strict';
// Reserved word lists for various dialects of the language
var reservedWords = {
3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
5: "class enum extends super const export import",
6: "enum",
strict: "implements interface let package private protected public static yield",
strictBind: "eval arguments"
}
// And the keywords
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"
var keywords = {
5: ecma5AndLessKeywords,
6: ecma5AndLessKeywords + " const class extends export import super"
}
// ## Character categories
// Big ugly regular expressions that match characters in the
// whitespace, identifier, and identifier-start categories. These
// are only applied when a character is found to actually have a
// code point above 128.
// Generated by `bin/generate-identifier-regex.js`.
var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
// These are a run-length and offset encoded representation of the
// >0xffff code points that are a valid part of identifiers. The
// offset starts at 0x10000, and each pair of numbers represents an
// offset to the next range, and then a size of the range. They were
// generated by bin/generate-identifier-regex.js
// eslint-disable-next-line comma-spacing
var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541]
// eslint-disable-next-line comma-spacing
var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]
// This has a complexity linear to the value of the code. The
// assumption is that looking up astral identifier characters is
// rare.
function isInAstralSet(code, set) {
var pos = 0x10000
for (var i = 0; i < set.length; i += 2) {
pos += set[i]
if (pos > code) return false
pos += set[i + 1]
if (pos >= code) return true
}
}
// Test whether a given character code starts an identifier.
function isIdentifierStart(code, astral) {
if (code < 65) return code === 36
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes)
}
// Test whether a given character is part of an identifier.
function isIdentifierChar(code, astral) {
if (code < 48) return code === 36
if (code < 58) return true
if (code < 65) return false
if (code < 91) return true
if (code < 97) return code === 95
if (code < 123) return true
if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code))
if (astral === false) return false
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
}
// ## Token types
// The assignment of fine-grained, information-carrying type objects
// allows the tokenizer to store the information it has about a
// token in a way that is very cheap for the parser to look up.
// All token type variables start with an underscore, to make them
// easy to recognize.
// The `beforeExpr` property is used to disambiguate between regular
// expressions and divisions. It is set on all token types that can
// be followed by an expression (thus, a slash after them would be a
// regular expression).
//
// The `startsExpr` property is used to check if the token ends a
// `yield` expression. It is set on all token types that either can
// directly start an expression (like a quotation mark) or can
// continue an expression (like the body of a string).
//
// `isLoop` marks a keyword as starting a loop, which is important
// to know when parsing a label, in order to allow or disallow
// continue jumps to that label.
var TokenType = function TokenType(label, conf) {
if ( conf === void 0 ) conf = {};
this.label = label
this.keyword = conf.keyword
this.beforeExpr = !!conf.beforeExpr
this.startsExpr = !!conf.startsExpr
this.isLoop = !!conf.isLoop
this.isAssign = !!conf.isAssign
this.prefix = !!conf.prefix
this.postfix = !!conf.postfix
this.binop = conf.binop || null
this.updateContext = null
};
function binop(name, prec) {
return new TokenType(name, {beforeExpr: true, binop: prec})
}
var beforeExpr = {beforeExpr: true};
var startsExpr = {startsExpr: true};
// Map keyword names to token types.
var keywordTypes = {}
// Succinct definitions of keyword token types
function kw(name, options) {
if ( options === void 0 ) options = {};
options.keyword = name
return keywordTypes[name] = new TokenType(name, options)
}
var tt = {
num: new TokenType("num", startsExpr),
regexp: new TokenType("regexp", startsExpr),
string: new TokenType("string", startsExpr),
name: new TokenType("name", startsExpr),
eof: new TokenType("eof"),
// Punctuation token types.
bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
bracketR: new TokenType("]"),
braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
braceR: new TokenType("}"),
parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
parenR: new TokenType(")"),
comma: new TokenType(",", beforeExpr),
semi: new TokenType(";", beforeExpr),
colon: new TokenType(":", beforeExpr),
dot: new TokenType("."),
question: new TokenType("?", beforeExpr),
arrow: new TokenType("=>", beforeExpr),
template: new TokenType("template"),
ellipsis: new TokenType("...", beforeExpr),
backQuote: new TokenType("`", startsExpr),
dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
// Operators. These carry several kinds of properties to help the
// parser use them properly (the presence of these properties is
// what categorizes them as operators).
//
// `binop`, when present, specifies that this operator is a binary
// operator, and will refer to its precedence.
//
// `prefix` and `postfix` mark the operator as a prefix or postfix
// unary operator.
//
// `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
// binary operators with a very low precedence, that should result
// in AssignmentExpression nodes.
eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
logicalOR: binop("||", 1),
logicalAND: binop("&&", 2),
bitwiseOR: binop("|", 3),
bitwiseXOR: binop("^", 4),
bitwiseAND: binop("&", 5),
equality: binop("==/!=", 6),
relational: binop("</>", 7),
bitShift: binop("<</>>", 8),
plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
modulo: binop("%", 10),
star: binop("*", 10),
slash: binop("/", 10),
starstar: new TokenType("**", {beforeExpr: true}),
// Keyword token types.
_break: kw("break"),
_case: kw("case", beforeExpr),
_catch: kw("catch"),
_continue: kw("continue"),
_debugger: kw("debugger"),
_default: kw("default", beforeExpr),
_do: kw("do", {isLoop: true, beforeExpr: true}),
_else: kw("else", beforeExpr),
_finally: kw("finally"),
_for: kw("for", {isLoop: true}),
_function: kw("function", startsExpr),
_if: kw("if"),
_return: kw("return", beforeExpr),
_switch: kw("switch"),
_throw: kw("throw", beforeExpr),
_try: kw("try"),
_var: kw("var"),
_const: kw("const"),
_while: kw("while", {isLoop: true}),
_with: kw("with"),
_new: kw("new", {beforeExpr: true, startsExpr: true}),
_this: kw("this", startsExpr),
_super: kw("super", startsExpr),
_class: kw("class"),
_extends: kw("extends", beforeExpr),
_export: kw("export"),
_import: kw("import"),
_null: kw("null", startsExpr),
_true: kw("true", startsExpr),
_false: kw("false", startsExpr),
_in: kw("in", {beforeExpr: true, binop: 7}),
_instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
_typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
_void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
_delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
}
// Matches a whole line break (where CRLF is considered a single
// line break). Used to count lines.
var lineBreak = /\r\n?|\n|\u2028|\u2029/
var lineBreakG = new RegExp(lineBreak.source, "g")
function isNewLine(code) {
return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
}
var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g
var ref = Object.prototype;
var hasOwnProperty = ref.hasOwnProperty;
var toString = ref.toString;
// Checks if an object has a property.
function has(obj, propName) {
return hasOwnProperty.call(obj, propName)
}
var isArray = Array.isArray || (function (obj) { return (
toString.call(obj) === "[object Array]"
); })
// These are used when `options.locations` is on, for the
// `startLoc` and `endLoc` properties.
var Position = function Position(line, col) {
this.line = line
this.column = col
};
Position.prototype.offset = function offset (n) {
return new Position(this.line, this.column + n)
};
var SourceLocation = function SourceLocation(p, start, end) {
this.start = start
this.end = end
if (p.sourceFile !== null) this.source = p.sourceFile
};
// The `getLineInfo` function is mostly useful when the
// `locations` option is off (for performance reasons) and you
// want to find the line/column position for a given character
// offset. `input` should be the code string that the offset refers
// into.
function getLineInfo(input, offset) {
for (var line = 1, cur = 0;;) {
lineBreakG.lastIndex = cur
var match = lineBreakG.exec(input)
if (match && match.index < offset) {
++line
cur = match.index + match[0].length
} else {
return new Position(line, offset - cur)
}
}
}
// A second optional argument can be given to further configure
// the parser process. These options are recognized:
var defaultOptions = {
// `ecmaVersion` indicates the ECMAScript version to parse. Must
// be either 3, 5, 6 (2015), 7 (2016), or 8 (2017). This influences support
// for strict mode, the set of reserved words, and support for
// new syntax features. The default is 7.
ecmaVersion: 7,
// `sourceType` indicates the mode the code should be parsed in.
// Can be either `"script"` or `"module"`. This influences global
// strict mode and parsing of `import` and `export` declarations.
sourceType: "script",
// `onInsertedSemicolon` can be a callback that will be called
// when a semicolon is automatically inserted. It will be passed
// th position of the comma as an offset, and if `locations` is
// enabled, it is given the location as a `{line, column}` object
// as second argument.
onInsertedSemicolon: null,
// `onTrailingComma` is similar to `onInsertedSemicolon`, but for
// trailing commas.
onTrailingComma: null,
// By default, reserved words are only enforced if ecmaVersion >= 5.
// Set `allowReserved` to a boolean value to explicitly turn this on
// an off. When this option has the value "never", reserved words
// and keywords can also not be used as property names.
allowReserved: null,
// When enabled, a return at the top level is not considered an
// error.
allowReturnOutsideFunction: false,
// When enabled, import/export statements are not constrained to
// appearing at the top of the program.
allowImportExportEverywhere: false,
// When enabled, hashbang directive in the beginning of file
// is allowed and treated as a line comment.
allowHashBang: false,
// When `locations` is on, `loc` properties holding objects with
// `start` and `end` properties in `{line, column}` form (with
// line being 1-based and column 0-based) will be attached to the
// nodes.
locations: false,
// A function can be passed as `onToken` option, which will
// cause Acorn to call that function with object in the same
// format as tokens returned from `tokenizer().getToken()`. Note
// that you are not allowed to call the parser from the
// callback—that will corrupt its internal state.
onToken: null,
// A function can be passed as `onComment` option, which will
// cause Acorn to call that function with `(block, text, start,
// end)` parameters whenever a comment is skipped. `block` is a
// boolean indicating whether this is a block (`/* */`) comment,
// `text` is the content of the comment, and `start` and `end` are
// character offsets that denote the start and end of the comment.
// When the `locations` option is on, two more parameters are
// passed, the full `{line, column}` locations of the start and
// end of the comments. Note that you are not allowed to call the
// parser from the callback—that will corrupt its internal state.
onComment: null,
// Nodes have their start and end characters offsets recorded in
// `start` and `end` properties (directly on the node, rather than
// the `loc` object, which holds line/column data. To also add a
// [semi-standardized][range] `range` property holding a `[start,
// end]` array with the same numbers, set the `ranges` option to
// `true`.
//
// [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
ranges: false,
// It is possible to parse multiple files into a single AST by
// passing the tree produced by parsing the first file as
// `program` option in subsequent parses. This will add the
// toplevel forms of the parsed file to the `Program` (top) node
// of an existing parse tree.
program: null,
// When `locations` is on, you can pass this to record the source
// file in every node's `loc` object.
sourceFile: null,
// This value, if given, is stored in every node, whether
// `locations` is on or off.
directSourceFile: null,
// When enabled, parenthesized expressions are represented by
// (non-standard) ParenthesizedExpression nodes
preserveParens: false,
plugins: {}
}
// Interpret and default an options object
function getOptions(opts) {
var options = {}
for (var opt in defaultOptions)
options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
if (options.ecmaVersion >= 2015)
options.ecmaVersion -= 2009
if (options.allowReserved == null)
options.allowReserved = options.ecmaVersion < 5
if (isArray(options.onToken)) {
var tokens = options.onToken
options.onToken = function (token) { return tokens.push(token); }
}
if (isArray(options.onComment))
options.onComment = pushComment(options, options.onComment)
return options
}
function pushComment(options, array) {
return function(block, text, start, end, startLoc, endLoc) {
var comment = {
type: block ? "Block" : "Line",
value: text,
start: start,
end: end
}
if (options.locations)
comment.loc = new SourceLocation(this, startLoc, endLoc)
if (options.ranges)
comment.range = [start, end]
array.push(comment)
}
}
// Registered plugins
var plugins = {}
function keywordRegexp(words) {
return new RegExp("^(" + words.replace(/ /g, "|") + ")$")
}
var Parser = function Parser(options, input, startPos) {
this.options = options = getOptions(options)
this.sourceFile = options.sourceFile
this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])
var reserved = ""
if (!options.allowReserved) {
for (var v = options.ecmaVersion;; v--)
if (reserved = reservedWords[v]) break
if (options.sourceType == "module") reserved += " await"
}
this.reservedWords = keywordRegexp(reserved)
var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict
this.reservedWordsStrict = keywordRegexp(reservedStrict)
this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind)
this.input = String(input)
// Used to signal to callers of `readWord1` whether the word
// contained any escape sequences. This is needed because words with
// escape sequences must not be interpreted as keywords.
this.containsEsc = false
// Load plugins
this.loadPlugins(options.plugins)
// Set up token state
// The current position of the tokenizer in the input.
if (startPos) {
this.pos = startPos
this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1
this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
} else {
this.pos = this.lineStart = 0
this.curLine = 1
}
// Properties of the current token:
// Its type
this.type = tt.eof
// For tokens that include more information than their type, the value
this.value = null
// Its start and end offset
this.start = this.end = this.pos
// And, if locations are used, the {line, column} object
// corresponding to those offsets
this.startLoc = this.endLoc = this.curPosition()
// Position information for the previous token
this.lastTokEndLoc = this.lastTokStartLoc = null
this.lastTokStart = this.lastTokEnd = this.pos
// The context stack is used to superficially track syntactic
// context to predict whether a regular expression is allowed in a
// given position.
this.context = this.initialContext()
this.exprAllowed = true
// Figure out if it's a module code.
this.inModule = options.sourceType === "module"
this.strict = this.inModule || this.strictDirective(this.pos)
// Used to signify the start of a potential arrow function
this.potentialArrowAt = -1
// Flags to track whether we are in a function, a generator, an async function.
this.inFunction = this.inGenerator = this.inAsync = false
// Positions to delayed-check that yield/await does not exist in default parameters.
this.yieldPos = this.awaitPos = 0
// Labels in scope.
this.labels = []
// If enabled, skip leading hashbang line.
if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
this.skipLineComment(2)
// Scope tracking for duplicate variable names (see scope.js)
this.scopeStack = []
this.enterFunctionScope()
};
// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
Parser.prototype.extend = function extend (name, f) {
this[name] = f(this[name])
};
Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
var this$1 = this;
for (var name in pluginConfigs) {
var plugin = plugins[name]
if (!plugin) throw new Error("Plugin '" + name + "' not found")
plugin(this$1, pluginConfigs[name])
}
};
Parser.prototype.parse = function parse () {
var node = this.options.program || this.startNode()
this.nextToken()
return this.parseTopLevel(node)
};
var pp = Parser.prototype
// ## Parser utilities
var literal = /^(?:'((?:[^']|\.)*)'|"((?:[^"]|\.)*)"|;)/
pp.strictDirective = function(start) {
var this$1 = this;
for (;;) {
skipWhiteSpace.lastIndex = start
start += skipWhiteSpace.exec(this$1.input)[0].length
var match = literal.exec(this$1.input.slice(start))
if (!match) return false
if ((match[1] || match[2]) == "use strict") return true
start += match[0].length
}
}
// Predicate that tests whether the next token is of the given
// type, and if yes, consumes it as a side effect.
pp.eat = function(type) {
if (this.type === type) {
this.next()
return true
} else {
return false
}
}
// Tests whether parsed token is a contextual keyword.
pp.isContextual = function(name) {
return this.type === tt.name && this.value === name
}
// Consumes contextual keyword if possible.
pp.eatContextual = function(name) {
return this.value === name && this.eat(tt.name)
}
// Asserts that following token is given contextual keyword.
pp.expectContextual = function(name) {
if (!this.eatContextual(name)) this.unexpected()
}
// Test whether a semicolon can be inserted at the current position.
pp.canInsertSemicolon = function() {
return this.type === tt.eof ||
this.type === tt.braceR ||
lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
}
pp.insertSemicolon = function() {
if (this.canInsertSemicolon()) {
if (this.options.onInsertedSemicolon)
this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
return true
}
}
// Consume a semicolon, or, failing that, see if we are allowed to
// pretend that there is a semicolon at this position.
pp.semicolon = function() {
if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
}
pp.afterTrailingComma = function(tokType, notNext) {
if (this.type == tokType) {
if (this.options.onTrailingComma)
this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
if (!notNext)
this.next()
return true
}
}
// Expect a token of a given type. If found, consume it, otherwise,
// raise an unexpected token error.
pp.expect = function(type) {
this.eat(type) || this.unexpected()
}
// Raise an unexpected token error.
pp.unexpected = function(pos) {
this.raise(pos != null ? pos : this.start, "Unexpected token")
}
var DestructuringErrors = function DestructuringErrors() {
this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = -1
};
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
if (!refDestructuringErrors) return
if (refDestructuringErrors.trailingComma > -1)
this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element")
var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind
if (parens > -1) this.raiseRecoverable(parens, "Parenthesized pattern")
}
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
var pos = refDestructuringErrors ? refDestructuringErrors.shorthandAssign : -1
if (!andThrow) return pos >= 0
if (pos > -1) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns")
}
pp.checkYieldAwaitInDefaultParams = function() {
if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
this.raise(this.yieldPos, "Yield expression cannot be a default value")
if (this.awaitPos)
this.raise(this.awaitPos, "Await expression cannot be a default value")
}
pp.isSimpleAssignTarget = function(expr) {
if (expr.type === "ParenthesizedExpression")
return this.isSimpleAssignTarget(expr.expression)
return expr.type === "Identifier" || expr.type === "MemberExpression"
}
var pp$1 = Parser.prototype
// ### Statement parsing
// Parse a program. Initializes the parser, reads any number of
// statements, and wraps them in a Program node. Optionally takes a
// `program` argument. If present, the statements will be appended
// to its body instead of creating a new node.
pp$1.parseTopLevel = function(node) {
var this$1 = this;
var exports = {}
if (!node.body) node.body = []
while (this.type !== tt.eof) {
var stmt = this$1.parseStatement(true, true, exports)
node.body.push(stmt)
}
this.next()
if (this.options.ecmaVersion >= 6) {
node.sourceType = this.options.sourceType
}
return this.finishNode(node, "Program")
}
var loopLabel = {kind: "loop"};
var switchLabel = {kind: "switch"};
pp$1.isLet = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
if (nextCh === 91 || nextCh == 123) return true // '{' and '['
if (isIdentifierStart(nextCh, true)) {
var pos = next + 1
while (isIdentifierChar(this.input.charCodeAt(pos), true)) ++pos
var ident = this.input.slice(next, pos)
if (!this.isKeyword(ident)) return true
}
return false
}
// check 'async [no LineTerminator here] function'
// - 'async /*foo*/ function' is OK.
// - 'async /*\n*/ function' is invalid.
pp$1.isAsyncFunction = function() {
if (this.type !== tt.name || this.options.ecmaVersion < 8 || this.value != "async")
return false
skipWhiteSpace.lastIndex = this.pos
var skip = skipWhiteSpace.exec(this.input)
var next = this.pos + skip[0].length
return !lineBreak.test(this.input.slice(this.pos, next)) &&
this.input.slice(next, next + 8) === "function" &&
(next + 8 == this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
}
// Parse a single statement.
//
// If expecting a statement and finding a slash operator, parse a
// regular expression literal. This is to handle cases like
// `if (foo) /blah/.exec(foo)`, where looking at the previous token
// does not help.
pp$1.parseStatement = function(declaration, topLevel, exports) {
var starttype = this.type, node = this.startNode(), kind
if (this.isLet()) {
starttype = tt._var
kind = "let"
}
// Most types of statements are recognized by the keyword they
// start with. Many are trivial to parse, some require a bit of
// complexity.
switch (starttype) {
case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
case tt._debugger: return this.parseDebuggerStatement(node)
case tt._do: return this.parseDoStatement(node)
case tt._for: return this.parseForStatement(node)
case tt._function:
if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
return this.parseFunctionStatement(node, false)
case tt._class:
if (!declaration) this.unexpected()
return this.parseClass(node, true)
case tt._if: return this.parseIfStatement(node)
case tt._return: return this.parseReturnStatement(node)
case tt._switch: return this.parseSwitchStatement(node)
case tt._throw: return this.parseThrowStatement(node)
case tt._try: return this.parseTryStatement(node)
case tt._const: case tt._var:
kind = kind || this.value
if (!declaration && kind != "var") this.unexpected()
return this.parseVarStatement(node, kind)
case tt._while: return this.parseWhileStatement(node)
case tt._with: return this.parseWithStatement(node)
case tt.braceL: return this.parseBlock()
case tt.semi: return this.parseEmptyStatement(node)
case tt._export:
case tt._import:
if (!this.options.allowImportExportEverywhere) {
if (!topLevel)
this.raise(this.start, "'import' and 'export' may only appear at the top level")
if (!this.inModule)
this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
}
return starttype === tt._import ? this.parseImport(node) : this.parseExport(node, exports)
// If the statement does not start with a statement keyword or a
// brace, it's an ExpressionStatement or LabeledStatement. We
// simply start parsing an expression, and afterwards, if the
// next token is a colon and the expression was a simple
// Identifier node, we switch to interpreting it as a label.
default:
if (this.isAsyncFunction() && declaration) {
this.next()
return this.parseFunctionStatement(node, true)
}
var maybeName = this.value, expr = this.parseExpression()
if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
return this.parseLabeledStatement(node, maybeName, expr)
else return this.parseExpressionStatement(node, expr)
}
}
pp$1.parseBreakContinueStatement = function(node, keyword) {
var this$1 = this;
var isBreak = keyword == "break"
this.next()
if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
else if (this.type !== tt.name) this.unexpected()
else {
node.label = this.parseIdent()
this.semicolon()
}
// Verify that there is an actual destination to break or
// continue to.
var i = 0
for (; i < this.labels.length; ++i) {
var lab = this$1.labels[i]
if (node.label == null || lab.name === node.label.name) {
if (lab.kind != null && (isBreak || lab.kind === "loop")) break
if (node.label && isBreak) break
}
}
if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
}
pp$1.parseDebuggerStatement = function(node) {
this.next()
this.semicolon()
return this.finishNode(node, "DebuggerStatement")
}
pp$1.parseDoStatement = function(node) {
this.next()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
this.expect(tt._while)
node.test = this.parseParenExpression()
if (this.options.ecmaVersion >= 6)
this.eat(tt.semi)
else
this.semicolon()
return this.finishNode(node, "DoWhileStatement")
}
// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
// loop is non-trivial. Basically, we have to parse the init `var`
// statement or expression, disallowing the `in` operator (see
// the second parameter to `parseExpression`), and then check
// whether the next token is `in` or `of`. When there is no init
// part (semicolon immediately after the opening parenthesis), it
// is a regular `for` loop.
pp$1.parseForStatement = function(node) {
this.next()
this.labels.push(loopLabel)
this.enterLexicalScope()
this.expect(tt.parenL)
if (this.type === tt.semi) return this.parseFor(node, null)
var isLet = this.isLet()
if (this.type === tt._var || this.type === tt._const || isLet) {
var init$1 = this.startNode(), kind = isLet ? "let" : this.value
this.next()
this.parseVar(init$1, true, kind)
this.finishNode(init$1, "VariableDeclaration")
if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
!(kind !== "var" && init$1.declarations[0].init))
return this.parseForIn(node, init$1)
return this.parseFor(node, init$1)
}
var refDestructuringErrors = new DestructuringErrors
var init = this.parseExpression(true, refDestructuringErrors)
if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
this.toAssignable(init)
this.checkLVal(init)
this.checkPatternErrors(refDestructuringErrors, true)
return this.parseForIn(node, init)
} else {
this.checkExpressionErrors(refDestructuringErrors, true)
}
return this.parseFor(node, init)
}
pp$1.parseFunctionStatement = function(node, isAsync) {
this.next()
return this.parseFunction(node, true, false, isAsync)
}
pp$1.isFunction = function() {
return this.type === tt._function || this.isAsyncFunction()
}
pp$1.parseIfStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
// allow function declarations in branches, but only in non-strict mode
node.consequent = this.parseStatement(!this.strict && this.isFunction())
node.alternate = this.eat(tt._else) ? this.parseStatement(!this.strict && this.isFunction()) : null
return this.finishNode(node, "IfStatement")
}
pp$1.parseReturnStatement = function(node) {
if (!this.inFunction && !this.options.allowReturnOutsideFunction)
this.raise(this.start, "'return' outside of function")
this.next()
// In `return` (and `break`/`continue`), the keywords with
// optional arguments, we eagerly look for a semicolon or the
// possibility to insert one.
if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
else { node.argument = this.parseExpression(); this.semicolon() }
return this.finishNode(node, "ReturnStatement")
}
pp$1.parseSwitchStatement = function(node) {
var this$1 = this;
this.next()
node.discriminant = this.parseParenExpression()
node.cases = []
this.expect(tt.braceL)
this.labels.push(switchLabel)
this.enterLexicalScope()
// Statements under must be grouped (by label) in SwitchCase
// nodes. `cur` is used to keep the node that we are currently
// adding statements to.
var cur
for (var sawDefault = false; this.type != tt.braceR;) {
if (this$1.type === tt._case || this$1.type === tt._default) {
var isCase = this$1.type === tt._case
if (cur) this$1.finishNode(cur, "SwitchCase")
node.cases.push(cur = this$1.startNode())
cur.consequent = []
this$1.next()
if (isCase) {
cur.test = this$1.parseExpression()
} else {
if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses")
sawDefault = true
cur.test = null
}
this$1.expect(tt.colon)
} else {
if (!cur) this$1.unexpected()
cur.consequent.push(this$1.parseStatement(true))
}
}
this.exitLexicalScope()
if (cur) this.finishNode(cur, "SwitchCase")
this.next() // Closing brace
this.labels.pop()
return this.finishNode(node, "SwitchStatement")
}
pp$1.parseThrowStatement = function(node) {
this.next()
if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
this.raise(this.lastTokEnd, "Illegal newline after throw")
node.argument = this.parseExpression()
this.semicolon()
return this.finishNode(node, "ThrowStatement")
}
// Reused empty array added for node fields that are always empty.
var empty = []
pp$1.parseTryStatement = function(node) {
this.next()
node.block = this.parseBlock()
node.handler = null
if (this.type === tt._catch) {
var clause = this.startNode()
this.next()
this.expect(tt.parenL)
clause.param = this.parseBindingAtom()
this.enterLexicalScope()
this.checkLVal(clause.param, "let")
this.expect(tt.parenR)
clause.body = this.parseBlock(false)
this.exitLexicalScope()
node.handler = this.finishNode(clause, "CatchClause")
}
node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
if (!node.handler && !node.finalizer)
this.raise(node.start, "Missing catch or finally clause")
return this.finishNode(node, "TryStatement")
}
pp$1.parseVarStatement = function(node, kind) {
this.next()
this.parseVar(node, false, kind)
this.semicolon()
return this.finishNode(node, "VariableDeclaration")
}
pp$1.parseWhileStatement = function(node) {
this.next()
node.test = this.parseParenExpression()
this.labels.push(loopLabel)
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "WhileStatement")
}
pp$1.parseWithStatement = function(node) {
if (this.strict) this.raise(this.start, "'with' in strict mode")
this.next()
node.object = this.parseParenExpression()
node.body = this.parseStatement(false)
return this.finishNode(node, "WithStatement")
}
pp$1.parseEmptyStatement = function(node) {
this.next()
return this.finishNode(node, "EmptyStatement")
}
pp$1.parseLabeledStatement = function(node, maybeName, expr) {
var this$1 = this;
for (var i = 0; i < this.labels.length; ++i)
if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared")
var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) {
var label = this$1.labels[i$1]
if (label.statementStart == node.start) {
label.statementStart = this$1.start
label.kind = kind
} else break
}
this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
node.body = this.parseStatement(true)
if (node.body.type == "ClassDeclaration" ||
node.body.type == "VariableDeclaration" && node.body.kind != "var" ||
node.body.type == "FunctionDeclaration" && (this.strict || node.body.generator))
this.raiseRecoverable(node.body.start, "Invalid labeled declaration")
this.labels.pop()
node.label = expr
return this.finishNode(node, "LabeledStatement")
}
pp$1.parseExpressionStatement = function(node, expr) {
node.expression = expr
this.semicolon()
return this.finishNode(node, "ExpressionStatement")
}
// Parse a semicolon-enclosed block of statements, handling `"use
// strict"` declarations when `allowStrict` is true (used for
// function bodies).
pp$1.parseBlock = function(createNewLexicalScope) {
var this$1 = this;
if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
var node = this.startNode()
node.body = []
this.expect(tt.braceL)
if (createNewLexicalScope) {
this.enterLexicalScope()
}
while (!this.eat(tt.braceR)) {
var stmt = this$1.parseStatement(true)
node.body.push(stmt)
}
if (createNewLexicalScope) {
this.exitLexicalScope()
}
return this.finishNode(node, "BlockStatement")
}
// Parse a regular `for` loop. The disambiguation code in
// `parseStatement` will already have parsed the init statement or
// expression.
pp$1.parseFor = function(node, init) {
node.init = init
this.expect(tt.semi)
node.test = this.type === tt.semi ? null : this.parseExpression()
this.expect(tt.semi)
node.update = this.type === tt.parenR ? null : this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, "ForStatement")
}
// Parse a `for`/`in` and `for`/`of` loop, which are almost
// same from parser's perspective.
pp$1.parseForIn = function(node, init) {
var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
this.next()
node.left = init
node.right = this.parseExpression()
this.expect(tt.parenR)
this.exitLexicalScope()
node.body = this.parseStatement(false)
this.labels.pop()
return this.finishNode(node, type)
}
// Parse a list of variable declarations.
pp$1.parseVar = function(node, isFor, kind) {
var this$1 = this;
node.declarations = []
node.kind = kind
for (;;) {
var decl = this$1.startNode()
this$1.parseVarId(decl, kind)
if (this$1.eat(tt.eq)) {
decl.init = this$1.parseMaybeAssign(isFor)
} else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
this$1.unexpected()
} else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) {
this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value")
} else {
decl.init = null
}
node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"))
if (!this$1.eat(tt.comma)) break
}
return node
}
pp$1.parseVarId = function(decl, kind) {
decl.id = this.parseBindingAtom(kind)
this.checkLVal(decl.id, kind, false)
}
// Parse a function declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseFunction = function(node, isStatement, allowExpressionBody, isAsync) {
this.initFunction(node)
if (this.options.ecmaVersion >= 6 && !isAsync)
node.generator = this.eat(tt.star)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
if (isStatement) {
node.id = isStatement === "nullableID" && this.type != tt.name ? null : this.parseIdent()
if (node.id) {
this.checkLVal(node.id, "var")
}
}
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
if (!isStatement)
node.id = this.type == tt.name ? this.parseIdent() : null
this.parseFunctionParams(node)
this.parseFunctionBody(node, allowExpressionBody)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
}
pp$1.parseFunctionParams = function(node) {
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8, true)
this.checkYieldAwaitInDefaultParams()
}
// Parse a class declaration or literal (depending on the
// `isStatement` parameter).
pp$1.parseClass = function(node, isStatement) {
var this$1 = this;
this.next()
this.parseClassId(node, isStatement)
this.parseClassSuper(node)
var classBody = this.startNode()
var hadConstructor = false
classBody.body = []
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (this$1.eat(tt.semi)) continue
var method = this$1.startNode()
var isGenerator = this$1.eat(tt.star)
var isAsync = false
var isMaybeStatic = this$1.type === tt.name && this$1.value === "static"
this$1.parsePropertyName(method)
method.static = isMaybeStatic && this$1.type !== tt.parenL
if (method.static) {
if (isGenerator) this$1.unexpected()
isGenerator = this$1.eat(tt.star)
this$1.parsePropertyName(method)
}
if (this$1.options.ecmaVersion >= 8 && !isGenerator && !method.computed &&
method.key.type === "Identifier" && method.key.name === "async" && this$1.type !== tt.parenL &&
!this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(method)
}
method.kind = "method"
var isGetSet = false
if (!method.computed) {
var key = method.key;
if (!isGenerator && !isAsync && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
isGetSet = true
method.kind = key.name
key = this$1.parsePropertyName(method)
}
if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
key.type === "Literal" && key.value === "constructor")) {
if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class")
if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier")
if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator")
if (isAsync) this$1.raise(key.start, "Constructor can't be an async method")
method.kind = "constructor"
hadConstructor = true
}
}
this$1.parseClassMethod(classBody, method, isGenerator, isAsync)
if (isGetSet) {
var paramCount = method.kind === "get" ? 0 : 1
if (method.value.params.length !== paramCount) {
var start = method.value.start
if (method.kind === "get")
this$1.raiseRecoverable(start, "getter should have no params")
else
this$1.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (method.kind === "set" && method.value.params[0].type === "RestElement")
this$1.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params")
}
}
}
node.body = this.finishNode(classBody, "ClassBody")
return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
}
pp$1.parseClassMethod = function(classBody, method, isGenerator, isAsync) {
method.value = this.parseMethod(isGenerator, isAsync)
classBody.body.push(this.finishNode(method, "MethodDefinition"))
}
pp$1.parseClassId = function(node, isStatement) {
node.id = this.type === tt.name ? this.parseIdent() : isStatement === true ? this.unexpected() : null
}
pp$1.parseClassSuper = function(node) {
node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
}
// Parses module export declaration.
pp$1.parseExport = function(node, exports) {
var this$1 = this;
this.next()
// export * from '...'
if (this.eat(tt.star)) {
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.semicolon()
return this.finishNode(node, "ExportAllDeclaration")
}
if (this.eat(tt._default)) { // export default ...
this.checkExport(exports, "default", this.lastTokStart)
var isAsync
if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
var fNode = this.startNode()
this.next()
if (isAsync) this.next()
node.declaration = this.parseFunction(fNode, "nullableID", false, isAsync)
} else if (this.type === tt._class) {
var cNode = this.startNode()
node.declaration = this.parseClass(cNode, "nullableID")
} else {
node.declaration = this.parseMaybeAssign()
this.semicolon()
}
return this.finishNode(node, "ExportDefaultDeclaration")
}
// export var|const|let|function|class ...
if (this.shouldParseExportStatement()) {
node.declaration = this.parseStatement(true)
if (node.declaration.type === "VariableDeclaration")
this.checkVariableExport(exports, node.declaration.declarations)
else
this.checkExport(exports, node.declaration.id.name, node.declaration.id.start)
node.specifiers = []
node.source = null
} else { // export { x, y as z } [from '...']
node.declaration = null
node.specifiers = this.parseExportSpecifiers(exports)
if (this.eatContextual("from")) {
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
} else {
// check for keywords used as local names
for (var i = 0; i < node.specifiers.length; i++) {
if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) {
this$1.unexpected(node.specifiers[i].local.start)
}
}
node.source = null
}
this.semicolon()
}
return this.finishNode(node, "ExportNamedDeclaration")
}
pp$1.checkExport = function(exports, name, pos) {
if (!exports) return
if (has(exports, name))
this.raiseRecoverable(pos, "Duplicate export '" + name + "'")
exports[name] = true
}
pp$1.checkPatternExport = function(exports, pat) {
var this$1 = this;
var type = pat.type
if (type == "Identifier")
this.checkExport(exports, pat.name, pat.start)
else if (type == "ObjectPattern")
for (var i = 0; i < pat.properties.length; ++i)
this$1.checkPatternExport(exports, pat.properties[i].value)
else if (type == "ArrayPattern")
for (var i$1 = 0; i$1 < pat.elements.length; ++i$1) {
var elt = pat.elements[i$1]
if (elt) this$1.checkPatternExport(exports, elt)
}
else if (type == "AssignmentPattern")
this.checkPatternExport(exports, pat.left)
else if (type == "ParenthesizedExpression")
this.checkPatternExport(exports, pat.expression)
}
pp$1.checkVariableExport = function(exports, decls) {
var this$1 = this;
if (!exports) return
for (var i = 0; i < decls.length; i++)
this$1.checkPatternExport(exports, decls[i].id)
}
pp$1.shouldParseExportStatement = function() {
return this.type.keyword === "var" ||
this.type.keyword === "const" ||
this.type.keyword === "class" ||
this.type.keyword === "function" ||
this.isLet() ||
this.isAsyncFunction()
}
// Parses a comma-separated list of module exports.
pp$1.parseExportSpecifiers = function(exports) {
var this$1 = this;
var nodes = [], first = true
// export { x, y as z } [from '...']
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node = this$1.startNode()
node.local = this$1.parseIdent(true)
node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local
this$1.checkExport(exports, node.exported.name, node.exported.start)
nodes.push(this$1.finishNode(node, "ExportSpecifier"))
}
return nodes
}
// Parses import declaration.
pp$1.parseImport = function(node) {
this.next()
// import '...'
if (this.type === tt.string) {
node.specifiers = empty
node.source = this.parseExprAtom()
} else {
node.specifiers = this.parseImportSpecifiers()
this.expectContextual("from")
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
}
this.semicolon()
return this.finishNode(node, "ImportDeclaration")
}
// Parses a comma-separated list of module imports.
pp$1.parseImportSpecifiers = function() {
var this$1 = this;
var nodes = [], first = true
if (this.type === tt.name) {
// import defaultObj, { x, y as z } from '...'
var node = this.startNode()
node.local = this.parseIdent()
this.checkLVal(node.local, "let")
nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
if (!this.eat(tt.comma)) return nodes
}
if (this.type === tt.star) {
var node$1 = this.startNode()
this.next()
this.expectContextual("as")
node$1.local = this.parseIdent()
this.checkLVal(node$1.local, "let")
nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"))
return nodes
}
this.expect(tt.braceL)
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var node$2 = this$1.startNode()
node$2.imported = this$1.parseIdent(true)
if (this$1.eatContextual("as")) {
node$2.local = this$1.parseIdent()
} else {
node$2.local = node$2.imported
if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start)
if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raiseRecoverable(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved")
}
this$1.checkLVal(node$2.local, "let")
nodes.push(this$1.finishNode(node$2, "ImportSpecifier"))
}
return nodes
}
var pp$2 = Parser.prototype
// Convert existing expression atom to assignable pattern
// if possible.
pp$2.toAssignable = function(node, isBinding) {
var this$1 = this;
if (this.options.ecmaVersion >= 6 && node) {
switch (node.type) {
case "Identifier":
if (this.inAsync && node.name === "await")
this.raise(node.start, "Can not use 'await' as identifier inside an async function")
break
case "ObjectPattern":
case "ArrayPattern":
break
case "ObjectExpression":
node.type = "ObjectPattern"
for (var i = 0; i < node.properties.length; i++) {
var prop = node.properties[i]
if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter")
this$1.toAssignable(prop.value, isBinding)
}
break
case "ArrayExpression":
node.type = "ArrayPattern"
this.toAssignableList(node.elements, isBinding)
break
case "AssignmentExpression":
if (node.operator === "=") {
node.type = "AssignmentPattern"
delete node.operator
this.toAssignable(node.left, isBinding)
// falls through to AssignmentPattern
} else {
this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
break
}
case "AssignmentPattern":
break
case "ParenthesizedExpression":
node.expression = this.toAssignable(node.expression, isBinding)
break
case "MemberExpression":
if (!isBinding) break
default:
this.raise(node.start, "Assigning to rvalue")
}
}
return node
}
// Convert list of expression atoms to binding list.
pp$2.toAssignableList = function(exprList, isBinding) {
var this$1 = this;
var end = exprList.length
if (end) {
var last = exprList[end - 1]
if (last && last.type == "RestElement") {
--end
} else if (last && last.type == "SpreadElement") {
last.type = "RestElement"
var arg = last.argument
this.toAssignable(arg, isBinding)
if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern")
this.unexpected(arg.start)
--end
}
if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
this.unexpected(last.argument.start)
}
for (var i = 0; i < end; i++) {
var elt = exprList[i]
if (elt) this$1.toAssignable(elt, isBinding)
}
return exprList
}
// Parses spread element.
pp$2.parseSpread = function(refDestructuringErrors) {
var node = this.startNode()
this.next()
node.argument = this.parseMaybeAssign(false, refDestructuringErrors)
return this.finishNode(node, "SpreadElement")
}
pp$2.parseRest = function(allowNonIdent) {
var node = this.startNode()
this.next()
// RestElement inside of a function parameter must be an identifier
if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected()
else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected()
return this.finishNode(node, "RestElement")
}
// Parses lvalue (assignable) atom.
pp$2.parseBindingAtom = function() {
if (this.options.ecmaVersion < 6) return this.parseIdent()
switch (this.type) {
case tt.name:
return this.parseIdent()
case tt.bracketL:
var node = this.startNode()
this.next()
node.elements = this.parseBindingList(tt.bracketR, true, true)
return this.finishNode(node, "ArrayPattern")
case tt.braceL:
return this.parseObj(true)
default:
this.unexpected()
}
}
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (first) first = false
else this$1.expect(tt.comma)
if (allowEmpty && this$1.type === tt.comma) {
elts.push(null)
} else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
break
} else if (this$1.type === tt.ellipsis) {
var rest = this$1.parseRest(allowNonIdent)
this$1.parseBindingListItem(rest)
elts.push(rest)
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
this$1.expect(close)
break
} else {
var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc)
this$1.parseBindingListItem(elem)
elts.push(elem)
}
}
return elts
}
pp$2.parseBindingListItem = function(param) {
return param
}
// Parses assignment pattern around given atom if possible.
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
left = left || this.parseBindingAtom()
if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.right = this.parseMaybeAssign()
return this.finishNode(node, "AssignmentPattern")
}
// Verify that a node is an lval — something that can be assigned
// to.
// bindingType can be either:
// 'var' indicating that the lval creates a 'var' binding
// 'let' indicating that the lval creates a lexical ('let' or 'const') binding
// 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
var this$1 = this;
switch (expr.type) {
case "Identifier":
if (this.strict && this.reservedWordsStrictBind.test(expr.name))
this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
if (checkClashes) {
if (has(checkClashes, expr.name))
this.raiseRecoverable(expr.start, "Argument name clash")
checkClashes[expr.name] = true
}
if (bindingType && bindingType !== "none") {
if (
bindingType === "var" && !this.canDeclareVarName(expr.name) ||
bindingType !== "var" && !this.canDeclareLexicalName(expr.name)
) {
this.raiseRecoverable(expr.start, ("Identifier '" + (expr.name) + "' has already been declared"))
}
if (bindingType === "var") {
this.declareVarName(expr.name)
} else {
this.declareLexicalName(expr.name)
}
}
break
case "MemberExpression":
if (bindingType) this.raiseRecoverable(expr.start, (bindingType ? "Binding" : "Assigning to") + " member expression")
break
case "ObjectPattern":
for (var i = 0; i < expr.properties.length; i++)
this$1.checkLVal(expr.properties[i].value, bindingType, checkClashes)
break
case "ArrayPattern":
for (var i$1 = 0; i$1 < expr.elements.length; i$1++) {
var elem = expr.elements[i$1]
if (elem) this$1.checkLVal(elem, bindingType, checkClashes)
}
break
case "AssignmentPattern":
this.checkLVal(expr.left, bindingType, checkClashes)
break
case "RestElement":
this.checkLVal(expr.argument, bindingType, checkClashes)
break
case "ParenthesizedExpression":
this.checkLVal(expr.expression, bindingType, checkClashes)
break
default:
this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue")
}
}
// A recursive descent parser operates by defining functions for all
// syntactic elements, and recursively calling those, each function
// advancing the input stream and returning an AST node. Precedence
// of constructs (for example, the fact that `!x[1]` means `!(x[1])`
// instead of `(!x)[1]` is handled by the fact that the parser
// function that parses unary prefix operators is called first, and
// in turn calls the function that parses `[]` subscripts — that
// way, it'll receive the node for `x[1]` already parsed, and wraps
// *that* in the unary operator node.
//
// Acorn uses an [operator precedence parser][opp] to handle binary
// operator precedence, because it is much more compact than using
// the technique outlined above, which uses different, nesting
// functions to specify precedence, for all of the ten binary
// precedence levels that JavaScript defines.
//
// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
var pp$3 = Parser.prototype
// Check if property name clashes with already added.
// Object/class getters and setters are not allowed to clash —
// either with each other or with an init property — and in
// strict mode, init properties are also not allowed to be repeated.
pp$3.checkPropClash = function(prop, propHash) {
if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
return
var key = prop.key;
var name
switch (key.type) {
case "Identifier": name = key.name; break
case "Literal": name = String(key.value); break
default: return
}
var kind = prop.kind;
if (this.options.ecmaVersion >= 6) {
if (name === "__proto__" && kind === "init") {
if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
propHash.proto = true
}
return
}
name = "$" + name
var other = propHash[name]
if (other) {
var redefinition
if (kind === "init") {
redefinition = this.strict && other.init || other.get || other.set
} else {
redefinition = other.init || other[kind]
}
if (redefinition)
this.raiseRecoverable(key.start, "Redefinition of property")
} else {
other = propHash[name] = {
init: false,
get: false,
set: false
}
}
other[kind] = true
}
// ### Expression parsing
// These nest, from the most general expression type at the top to
// 'atomic', nondivisible expression types at the bottom. Most of
// the functions will simply let the function(s) below them parse,
// and, *if* the syntactic construct they handle is present, wrap
// the AST node that the inner parser gave them in another node.
// Parse a full expression. The optional arguments are used to
// forbid the `in` operator (in for loops initalization expressions)
// and provide reference for storing '=' operator inside shorthand
// property assignment in contexts where both object expression
// and object pattern might appear (so it's possible to raise
// delayed syntax error at correct position).
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
if (this.type === tt.comma) {
var node = this.startNodeAt(startPos, startLoc)
node.expressions = [expr]
while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors))
return this.finishNode(node, "SequenceExpression")
}
return expr
}
// Parse an assignment expression. This includes applications of
// operators like `+=`.
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
if (this.inGenerator && this.isContextual("yield")) return this.parseYield()
var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1
if (refDestructuringErrors) {
oldParenAssign = refDestructuringErrors.parenthesizedAssign
oldTrailingComma = refDestructuringErrors.trailingComma
refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1
} else {
refDestructuringErrors = new DestructuringErrors
ownDestructuringErrors = true
}
var startPos = this.start, startLoc = this.startLoc
if (this.type == tt.parenL || this.type == tt.name)
this.potentialArrowAt = this.start
var left = this.parseMaybeConditional(noIn, refDestructuringErrors)
if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
if (this.type.isAssign) {
this.checkPatternErrors(refDestructuringErrors, true)
if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
var node = this.startNodeAt(startPos, startLoc)
node.operator = this.value
node.left = this.type === tt.eq ? this.toAssignable(left) : left
refDestructuringErrors.shorthandAssign = -1 // reset because shorthand default was used correctly
this.checkLVal(left)
this.next()
node.right = this.parseMaybeAssign(noIn)
return this.finishNode(node, "AssignmentExpression")
} else {
if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
}
if (oldParenAssign > -1) refDestructuringErrors.parenthesizedAssign = oldParenAssign
if (oldTrailingComma > -1) refDestructuringErrors.trailingComma = oldTrailingComma
return left
}
// Parse a ternary conditional (`?:`) operator.
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprOps(noIn, refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
if (this.eat(tt.question)) {
var node = this.startNodeAt(startPos, startLoc)
node.test = expr
node.consequent = this.parseMaybeAssign()
this.expect(tt.colon)
node.alternate = this.parseMaybeAssign(noIn)
return this.finishNode(node, "ConditionalExpression")
}
return expr
}
// Start the precedence parser.
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseMaybeUnary(refDestructuringErrors, false)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
return expr.start == startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
}
// Parse binary operators with the operator precedence parsing
// algorithm. `left` is the left-hand side of the operator.
// `minPrec` provides context that allows the function to stop and
// defer further parser to one of its callers when it encounters an
// operator that has a lower precedence than the set it is parsing.
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
var prec = this.type.binop
if (prec != null && (!noIn || this.type !== tt._in)) {
if (prec > minPrec) {
var logical = this.type === tt.logicalOR || this.type === tt.logicalAND
var op = this.value
this.next()
var startPos = this.start, startLoc = this.startLoc
var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
}
}
return left
}
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
var node = this.startNodeAt(startPos, startLoc)
node.left = left
node.operator = op
node.right = right
return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
}
// Parse unary operators, both prefix and postfix.
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, expr
if (this.inAsync && this.isContextual("await")) {
expr = this.parseAwait(refDestructuringErrors)
sawUnary = true
} else if (this.type.prefix) {
var node = this.startNode(), update = this.type === tt.incDec
node.operator = this.value
node.prefix = true
this.next()
node.argument = this.parseMaybeUnary(null, true)
this.checkExpressionErrors(refDestructuringErrors, true)
if (update) this.checkLVal(node.argument)
else if (this.strict && node.operator === "delete" &&
node.argument.type === "Identifier")
this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
else sawUnary = true
expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
} else {
expr = this.parseExprSubscripts(refDestructuringErrors)
if (this.checkExpressionErrors(refDestructuringErrors)) return expr
while (this.type.postfix && !this.canInsertSemicolon()) {
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.operator = this$1.value
node$1.prefix = false
node$1.argument = expr
this$1.checkLVal(expr)
this$1.next()
expr = this$1.finishNode(node$1, "UpdateExpression")
}
}
if (!sawUnary && this.eat(tt.starstar))
return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
else
return expr
}
// Parse call, dot, and `[]`-subscript expressions.
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
var startPos = this.start, startLoc = this.startLoc
var expr = this.parseExprAtom(refDestructuringErrors)
var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
var result = this.parseSubscripts(expr, startPos, startLoc)
if (refDestructuringErrors && result.type === "MemberExpression") {
if (refDestructuringErrors.parenthesizedAssign >= result.start) refDestructuringErrors.parenthesizedAssign = -1
if (refDestructuringErrors.parenthesizedBind >= result.start) refDestructuringErrors.parenthesizedBind = -1
}
return result
}
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
var this$1 = this;
var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
this.lastTokEnd == base.end && !this.canInsertSemicolon()
for (var computed;;) {
if ((computed = this$1.eat(tt.bracketL)) || this$1.eat(tt.dot)) {
var node = this$1.startNodeAt(startPos, startLoc)
node.object = base
node.property = computed ? this$1.parseExpression() : this$1.parseIdent(true)
node.computed = !!computed
if (computed) this$1.expect(tt.bracketR)
base = this$1.finishNode(node, "MemberExpression")
} else if (!noCalls && this$1.eat(tt.parenL)) {
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this$1.yieldPos, oldAwaitPos = this$1.awaitPos
this$1.yieldPos = 0
this$1.awaitPos = 0
var exprList = this$1.parseExprList(tt.parenR, this$1.options.ecmaVersion >= 8, false, refDestructuringErrors)
if (maybeAsyncArrow && !this$1.canInsertSemicolon() && this$1.eat(tt.arrow)) {
this$1.checkPatternErrors(refDestructuringErrors, false)
this$1.checkYieldAwaitInDefaultParams()
this$1.yieldPos = oldYieldPos
this$1.awaitPos = oldAwaitPos
return this$1.parseArrowExpression(this$1.startNodeAt(startPos, startLoc), exprList, true)
}
this$1.checkExpressionErrors(refDestructuringErrors, true)
this$1.yieldPos = oldYieldPos || this$1.yieldPos
this$1.awaitPos = oldAwaitPos || this$1.awaitPos
var node$1 = this$1.startNodeAt(startPos, startLoc)
node$1.callee = base
node$1.arguments = exprList
base = this$1.finishNode(node$1, "CallExpression")
} else if (this$1.type === tt.backQuote) {
var node$2 = this$1.startNodeAt(startPos, startLoc)
node$2.tag = base
node$2.quasi = this$1.parseTemplate()
base = this$1.finishNode(node$2, "TaggedTemplateExpression")
} else {
return base
}
}
}
// Parse an atomic expression — either a single token that is an
// expression, an expression started by a keyword like `function` or
// `new`, or an expression wrapped in punctuation like `()`, `[]`,
// or `{}`.
pp$3.parseExprAtom = function(refDestructuringErrors) {
var node, canBeArrow = this.potentialArrowAt == this.start
switch (this.type) {
case tt._super:
if (!this.inFunction)
this.raise(this.start, "'super' outside of function or class")
case tt._this:
var type = this.type === tt._this ? "ThisExpression" : "Super"
node = this.startNode()
this.next()
return this.finishNode(node, type)
case tt.name:
var startPos = this.start, startLoc = this.startLoc
var id = this.parseIdent(this.type !== tt.name)
if (this.options.ecmaVersion >= 8 && id.name === "async" && !this.canInsertSemicolon() && this.eat(tt._function))
return this.parseFunction(this.startNodeAt(startPos, startLoc), false, false, true)
if (canBeArrow && !this.canInsertSemicolon()) {
if (this.eat(tt.arrow))
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false)
if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === tt.name) {
id = this.parseIdent()
if (this.canInsertSemicolon() || !this.eat(tt.arrow))
this.unexpected()
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
}
}
return id
case tt.regexp:
var value = this.value
node = this.parseLiteral(value.value)
node.regex = {pattern: value.pattern, flags: value.flags}
return node
case tt.num: case tt.string:
return this.parseLiteral(this.value)
case tt._null: case tt._true: case tt._false:
node = this.startNode()
node.value = this.type === tt._null ? null : this.type === tt._true
node.raw = this.type.keyword
this.next()
return this.finishNode(node, "Literal")
case tt.parenL:
var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow)
if (refDestructuringErrors) {
if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
refDestructuringErrors.parenthesizedAssign = start
if (refDestructuringErrors.parenthesizedBind < 0)
refDestructuringErrors.parenthesizedBind = start
}
return expr
case tt.bracketL:
node = this.startNode()
this.next()
node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
return this.finishNode(node, "ArrayExpression")
case tt.braceL:
return this.parseObj(false, refDestructuringErrors)
case tt._function:
node = this.startNode()
this.next()
return this.parseFunction(node, false)
case tt._class:
return this.parseClass(this.startNode(), false)
case tt._new:
return this.parseNew()
case tt.backQuote:
return this.parseTemplate()
default:
this.unexpected()
}
}
pp$3.parseLiteral = function(value) {
var node = this.startNode()
node.value = value
node.raw = this.input.slice(this.start, this.end)
this.next()
return this.finishNode(node, "Literal")
}
pp$3.parseParenExpression = function() {
this.expect(tt.parenL)
var val = this.parseExpression()
this.expect(tt.parenR)
return val
}
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
var this$1 = this;
var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8
if (this.options.ecmaVersion >= 6) {
this.next()
var innerStartPos = this.start, innerStartLoc = this.startLoc
var exprList = [], first = true, lastIsComma = false
var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart, innerParenStart
this.yieldPos = 0
this.awaitPos = 0
while (this.type !== tt.parenR) {
first ? first = false : this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(tt.parenR, true)) {
lastIsComma = true
break
} else if (this$1.type === tt.ellipsis) {
spreadStart = this$1.start
exprList.push(this$1.parseParenItem(this$1.parseRest()))
if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
break
} else {
if (this$1.type === tt.parenL && !innerParenStart) {
innerParenStart = this$1.start
}
exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem))
}
}
var innerEndPos = this.start, innerEndLoc = this.startLoc
this.expect(tt.parenR)
if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
this.checkPatternErrors(refDestructuringErrors, false)
this.checkYieldAwaitInDefaultParams()
if (innerParenStart) this.unexpected(innerParenStart)
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
return this.parseParenArrowList(startPos, startLoc, exprList)
}
if (!exprList.length || lastIsComma) this.unexpected(this.lastTokStart)
if (spreadStart) this.unexpected(spreadStart)
this.checkExpressionErrors(refDestructuringErrors, true)
this.yieldPos = oldYieldPos || this.yieldPos
this.awaitPos = oldAwaitPos || this.awaitPos
if (exprList.length > 1) {
val = this.startNodeAt(innerStartPos, innerStartLoc)
val.expressions = exprList
this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
} else {
val = exprList[0]
}
} else {
val = this.parseParenExpression()
}
if (this.options.preserveParens) {
var par = this.startNodeAt(startPos, startLoc)
par.expression = val
return this.finishNode(par, "ParenthesizedExpression")
} else {
return val
}
}
pp$3.parseParenItem = function(item) {
return item
}
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
}
// New's precedence is slightly tricky. It must allow its argument to
// be a `[]` or dot subscript expression, but not a call — at least,
// not without wrapping it in parentheses. Thus, it uses the noCalls
// argument to parseSubscripts to prevent it from consuming the
// argument list.
var empty$1 = []
pp$3.parseNew = function() {
var node = this.startNode()
var meta = this.parseIdent(true)
if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
node.meta = meta
node.property = this.parseIdent(true)
if (node.property.name !== "target")
this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
if (!this.inFunction)
this.raiseRecoverable(node.start, "new.target can only be used in functions")
return this.finishNode(node, "MetaProperty")
}
var startPos = this.start, startLoc = this.startLoc
node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, this.options.ecmaVersion >= 8, false)
else node.arguments = empty$1
return this.finishNode(node, "NewExpression")
}
// Parse template expression.
pp$3.parseTemplateElement = function() {
var elem = this.startNode()
elem.value = {
raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
cooked: this.value
}
this.next()
elem.tail = this.type === tt.backQuote
return this.finishNode(elem, "TemplateElement")
}
pp$3.parseTemplate = function() {
var this$1 = this;
var node = this.startNode()
this.next()
node.expressions = []
var curElt = this.parseTemplateElement()
node.quasis = [curElt]
while (!curElt.tail) {
this$1.expect(tt.dollarBraceL)
node.expressions.push(this$1.parseExpression())
this$1.expect(tt.braceR)
node.quasis.push(curElt = this$1.parseTemplateElement())
}
this.next()
return this.finishNode(node, "TemplateLiteral")
}
// Parse an object literal or binding pattern.
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
var this$1 = this;
var node = this.startNode(), first = true, propHash = {}
node.properties = []
this.next()
while (!this.eat(tt.braceR)) {
if (!first) {
this$1.expect(tt.comma)
if (this$1.afterTrailingComma(tt.braceR)) break
} else first = false
var prop = this$1.startNode(), isGenerator, isAsync, startPos, startLoc
if (this$1.options.ecmaVersion >= 6) {
prop.method = false
prop.shorthand = false
if (isPattern || refDestructuringErrors) {
startPos = this$1.start
startLoc = this$1.startLoc
}
if (!isPattern)
isGenerator = this$1.eat(tt.star)
}
this$1.parsePropertyName(prop)
if (!isPattern && this$1.options.ecmaVersion >= 8 && !isGenerator && !prop.computed &&
prop.key.type === "Identifier" && prop.key.name === "async" && this$1.type !== tt.parenL &&
this$1.type !== tt.colon && !this$1.canInsertSemicolon()) {
isAsync = true
this$1.parsePropertyName(prop, refDestructuringErrors)
} else {
isAsync = false
}
this$1.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors)
this$1.checkPropClash(prop, propHash)
node.properties.push(this$1.finishNode(prop, "Property"))
}
return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
}
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors) {
if ((isGenerator || isAsync) && this.type === tt.colon)
this.unexpected()
if (this.eat(tt.colon)) {
prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
prop.kind = "init"
} else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
if (isPattern) this.unexpected()
prop.kind = "init"
prop.method = true
prop.value = this.parseMethod(isGenerator, isAsync)
} else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
(prop.key.name === "get" || prop.key.name === "set") &&
(this.type != tt.comma && this.type != tt.braceR)) {
if (isGenerator || isAsync || isPattern) this.unexpected()
prop.kind = prop.key.name
this.parsePropertyName(prop)
prop.value = this.parseMethod(false)
var paramCount = prop.kind === "get" ? 0 : 1
if (prop.value.params.length !== paramCount) {
var start = prop.value.start
if (prop.kind === "get")
this.raiseRecoverable(start, "getter should have no params")
else
this.raiseRecoverable(start, "setter should have exactly one param")
} else {
if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
}
} else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
if (this.keywords.test(prop.key.name) ||
(this.strict ? this.reservedWordsStrict : this.reservedWords).test(prop.key.name) ||
(this.inGenerator && prop.key.name == "yield") ||
(this.inAsync && prop.key.name == "await"))
this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property")
prop.kind = "init"
if (isPattern) {
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else if (this.type === tt.eq && refDestructuringErrors) {
if (refDestructuringErrors.shorthandAssign < 0)
refDestructuringErrors.shorthandAssign = this.start
prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
} else {
prop.value = prop.key
}
prop.shorthand = true
} else this.unexpected()
}
pp$3.parsePropertyName = function(prop) {
if (this.options.ecmaVersion >= 6) {
if (this.eat(tt.bracketL)) {
prop.computed = true
prop.key = this.parseMaybeAssign()
this.expect(tt.bracketR)
return prop.key
} else {
prop.computed = false
}
}
return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
}
// Initialize empty function node.
pp$3.initFunction = function(node) {
node.id = null
if (this.options.ecmaVersion >= 6) {
node.generator = false
node.expression = false
}
if (this.options.ecmaVersion >= 8)
node.async = false
}
// Parse object or class method.
pp$3.parseMethod = function(isGenerator, isAsync) {
var node = this.startNode(), oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.initFunction(node)
if (this.options.ecmaVersion >= 6)
node.generator = isGenerator
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = node.generator
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
this.enterFunctionScope()
this.expect(tt.parenL)
node.params = this.parseBindingList(tt.parenR, false, this.options.ecmaVersion >= 8)
this.checkYieldAwaitInDefaultParams()
this.parseFunctionBody(node, false)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "FunctionExpression")
}
// Parse arrow function expression with given parameters.
pp$3.parseArrowExpression = function(node, params, isAsync) {
var oldInGen = this.inGenerator, oldInAsync = this.inAsync,
oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldInFunc = this.inFunction
this.enterFunctionScope()
this.initFunction(node)
if (this.options.ecmaVersion >= 8)
node.async = !!isAsync
this.inGenerator = false
this.inAsync = node.async
this.yieldPos = 0
this.awaitPos = 0
this.inFunction = true
node.params = this.toAssignableList(params, true)
this.parseFunctionBody(node, true)
this.inGenerator = oldInGen
this.inAsync = oldInAsync
this.yieldPos = oldYieldPos
this.awaitPos = oldAwaitPos
this.inFunction = oldInFunc
return this.finishNode(node, "ArrowFunctionExpression")
}
// Parse function body and check parameters.
pp$3.parseFunctionBody = function(node, isArrowFunction) {
var isExpression = isArrowFunction && this.type !== tt.braceL
var oldStrict = this.strict, useStrict = false
if (isExpression) {
node.body = this.parseMaybeAssign()
node.expression = true
this.checkParams(node, false)
} else {
var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params)
if (!oldStrict || nonSimple) {
useStrict = this.strictDirective(this.end)
// If this is a strict mode function, verify that argument names
// are not repeated, and it does not try to bind the words `eval`
// or `arguments`.
if (useStrict && nonSimple)
this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list")
}
// Start a new scope with regard to labels and the `inFunction`
// flag (restore them to their old value afterwards).
var oldLabels = this.labels
this.labels = []
if (useStrict) this.strict = true
// Add the params to varDeclaredNames to ensure that an error is thrown
// if a let/const declaration in the function clashes with one of the params.
this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && this.isSimpleParamList(node.params))
node.body = this.parseBlock(false)
node.expression = false
this.labels = oldLabels
}
this.exitFunctionScope()
if (this.strict && node.id) {
// Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
this.checkLVal(node.id, "none")
}
this.strict = oldStrict
}
pp$3.isSimpleParamList = function(params) {
for (var i = 0; i < params.length; i++)
if (params[i].type !== "Identifier") return false
return true
}
// Checks function params for various disallowed patterns such as using "eval"
// or "arguments" and duplicate parameters.
pp$3.checkParams = function(node, allowDuplicates) {
var this$1 = this;
var nameHash = {}
for (var i = 0; i < node.params.length; i++) this$1.checkLVal(node.params[i], "var", allowDuplicates ? null : nameHash)
}
// Parses a comma-separated list of expressions, and returns them as
// an array. `close` is the token type that ends the list, and
// `allowEmpty` can be turned on to allow subsequent commas with
// nothing in between them to be parsed as `null` (which is needed
// for array literals).
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
var this$1 = this;
var elts = [], first = true
while (!this.eat(close)) {
if (!first) {
this$1.expect(tt.comma)
if (allowTrailingComma && this$1.afterTrailingComma(close)) break
} else first = false
var elt
if (allowEmpty && this$1.type === tt.comma)
elt = null
else if (this$1.type === tt.ellipsis) {
elt = this$1.parseSpread(refDestructuringErrors)
if (refDestructuringErrors && this$1.type === tt.comma && refDestructuringErrors.trailingComma < 0)
refDestructuringErrors.trailingComma = this$1.start
} else {
elt = this$1.parseMaybeAssign(false, refDestructuringErrors)
}
elts.push(elt)
}
return elts
}
// Parse the next token as an identifier. If `liberal` is true (used
// when parsing properties), it will also convert keywords into
// identifiers.
pp$3.parseIdent = function(liberal) {
var node = this.startNode()
if (liberal && this.options.allowReserved == "never") liberal = false
if (this.type === tt.name) {
if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) &&
(this.options.ecmaVersion >= 6 ||
this.input.slice(this.start, this.end).indexOf("\\") == -1))
this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved")
if (this.inGenerator && this.value === "yield")
this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator")
if (this.inAsync && this.value === "await")
this.raiseRecoverable(this.start, "Can not use 'await' as identifier inside an async function")
node.name = this.value
} else if (liberal && this.type.keyword) {
node.name = this.type.keyword
} else {
this.unexpected()
}
this.next()
return this.finishNode(node, "Identifier")
}
// Parses yield expression inside generator.
pp$3.parseYield = function() {
if (!this.yieldPos) this.yieldPos = this.start
var node = this.startNode()
this.next()
if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
node.delegate = false
node.argument = null
} else {
node.delegate = this.eat(tt.star)
node.argument = this.parseMaybeAssign()
}
return this.finishNode(node, "YieldExpression")
}
pp$3.parseAwait = function() {
if (!this.awaitPos) this.awaitPos = this.start
var node = this.startNode()
this.next()
node.argument = this.parseMaybeUnary(null, true)
return this.finishNode(node, "AwaitExpression")
}
var pp$4 = Parser.prototype
// This function is used to raise exceptions on parse errors. It
// takes an offset integer (into the current `input`) to indicate
// the location of the error, attaches the position to the end
// of the error message, and then raises a `SyntaxError` with that
// message.
pp$4.raise = function(pos, message) {
var loc = getLineInfo(this.input, pos)
message += " (" + loc.line + ":" + loc.column + ")"
var err = new SyntaxError(message)
err.pos = pos; err.loc = loc; err.raisedAt = this.pos
throw err
}
pp$4.raiseRecoverable = pp$4.raise
pp$4.curPosition = function() {
if (this.options.locations) {
return new Position(this.curLine, this.pos - this.lineStart)
}
}
var pp$5 = Parser.prototype
// Object.assign polyfill
var assign = Object.assign || function(target) {
var sources = [], len = arguments.length - 1;
while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
for (var i = 0; i < sources.length; i++) {
var source = sources[i]
for (var key in source) {
if (has(source, key)) {
target[key] = source[key]
}
}
}
return target
}
// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
pp$5.enterFunctionScope = function() {
// var: a hash of var-declared names in the current lexical scope
// lexical: a hash of lexically-declared names in the current lexical scope
// childVar: a hash of var-declared names in all child lexical scopes of the current lexical scope (within the current function scope)
// parentLexical: a hash of lexically-declared names in all parent lexical scopes of the current lexical scope (within the current function scope)
this.scopeStack.push({var: {}, lexical: {}, childVar: {}, parentLexical: {}})
}
pp$5.exitFunctionScope = function() {
this.scopeStack.pop()
}
pp$5.enterLexicalScope = function() {
var parentScope = this.scopeStack[this.scopeStack.length - 1]
var childScope = {var: {}, lexical: {}, childVar: {}, parentLexical: {}}
this.scopeStack.push(childScope)
assign(childScope.parentLexical, parentScope.lexical, parentScope.parentLexical)
}
pp$5.exitLexicalScope = function() {
var childScope = this.scopeStack.pop()
var parentScope = this.scopeStack[this.scopeStack.length - 1]
assign(parentScope.childVar, childScope.var, childScope.childVar)
}
/**
* A name can be declared with `var` if there are no variables with the same name declared with `let`/`const`
* in the current lexical scope or any of the parent lexical scopes in this function.
*/
pp$5.canDeclareVarName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.parentLexical, name)
}
/**
* A name can be declared with `let`/`const` if there are no variables with the same name declared with `let`/`const`
* in the current scope, and there are no variables with the same name declared with `var` in the current scope or in
* any child lexical scopes in this function.
*/
pp$5.canDeclareLexicalName = function(name) {
var currentScope = this.scopeStack[this.scopeStack.length - 1]
return !has(currentScope.lexical, name) && !has(currentScope.var, name) && !has(currentScope.childVar, name)
}
pp$5.declareVarName = function(name) {
this.scopeStack[this.scopeStack.length - 1].var[name] = true
}
pp$5.declareLexicalName = function(name) {
this.scopeStack[this.scopeStack.length - 1].lexical[name] = true
}
var Node = function Node(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
};
// Start an AST node, attaching a start offset.
var pp$6 = Parser.prototype
pp$6.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp$6.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp$6.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp$6.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
// The algorithm used to determine whether a regexp can appear at a
// given point in the program is loosely based on sweet.js' approach.
// See https://github.com/mozilla/sweet.js/wiki/design
var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
this.token = token
this.isExpr = !!isExpr
this.preserveSpace = !!preserveSpace
this.override = override
this.generator = !!generator
};
var types = {
b_stat: new TokContext("{", false),
b_expr: new TokContext("{", true),
b_tmpl: new TokContext("${", true),
p_stat: new TokContext("(", false),
p_expr: new TokContext("(", true),
q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }),
f_expr: new TokContext("function", true),
f_expr_gen: new TokContext("function", true, false, null, true),
f_gen: new TokContext("function", false, false, null, true)
}
var pp$7 = Parser.prototype
pp$7.initialContext = function() {
return [types.b_stat]
}
pp$7.braceIsBlock = function(prevType) {
if (prevType === tt.colon) {
var parent = this.curContext()
if (parent === types.b_stat || parent === types.b_expr)
return !parent.isExpr
}
if (prevType === tt._return)
return lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR || prevType == tt.arrow)
return true
if (prevType == tt.braceL)
return this.curContext() === types.b_stat
return !this.exprAllowed
}
pp$7.inGeneratorContext = function() {
var this$1 = this;
for (var i = this.context.length - 1; i >= 0; i--)
if (this$1.context[i].generator) return true
return false
}
pp$7.updateContext = function(prevType) {
var update, type = this.type
if (type.keyword && prevType == tt.dot)
this.exprAllowed = false
else if (update = type.updateContext)
update.call(this, prevType)
else
this.exprAllowed = type.beforeExpr
}
// Token-specific context update code
tt.parenR.updateContext = tt.braceR.updateContext = function() {
if (this.context.length == 1) {
this.exprAllowed = true
return
}
var out = this.context.pop(), cur
if (out === types.b_stat && (cur = this.curContext()) && cur.token === "function") {
this.context.pop()
this.exprAllowed = false
} else if (out === types.b_tmpl) {
this.exprAllowed = true
} else {
this.exprAllowed = !out.isExpr
}
}
tt.braceL.updateContext = function(prevType) {
this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr)
this.exprAllowed = true
}
tt.dollarBraceL.updateContext = function() {
this.context.push(types.b_tmpl)
this.exprAllowed = true
}
tt.parenL.updateContext = function(prevType) {
var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while
this.context.push(statementParens ? types.p_stat : types.p_expr)
this.exprAllowed = true
}
tt.incDec.updateContext = function() {
// tokExprAllowed stays unchanged
}
tt._function.updateContext = function(prevType) {
if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else &&
!((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat))
this.context.push(types.f_expr)
this.exprAllowed = false
}
tt.backQuote.updateContext = function() {
if (this.curContext() === types.q_tmpl)
this.context.pop()
else
this.context.push(types.q_tmpl)
this.exprAllowed = false
}
tt.star.updateContext = function(prevType) {
if (prevType == tt._function) {
if (this.curContext() === types.f_expr)
this.context[this.context.length - 1] = types.f_expr_gen
else
this.context.push(types.f_gen)
}
this.exprAllowed = true
}
tt.name.updateContext = function(prevType) {
var allowed = false
if (this.options.ecmaVersion >= 6) {
if (this.value == "of" && !this.exprAllowed ||
this.value == "yield" && this.inGeneratorContext())
allowed = true
}
this.exprAllowed = allowed
}
// Object type used to represent tokens. Note that normally, tokens
// simply exist as properties on the parser object. This is only
// used for the onToken callback and the external tokenizer.
var Token = function Token(p) {
this.type = p.type
this.value = p.value
this.start = p.start
this.end = p.end
if (p.options.locations)
this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
if (p.options.ranges)
this.range = [p.start, p.end]
};
// ## Tokenizer
var pp$8 = Parser.prototype
// Are we running under Rhino?
var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
// Move to the next token
pp$8.next = function() {
if (this.options.onToken)
this.options.onToken(new Token(this))
this.lastTokEnd = this.end
this.lastTokStart = this.start
this.lastTokEndLoc = this.endLoc
this.lastTokStartLoc = this.startLoc
this.nextToken()
}
pp$8.getToken = function() {
this.next()
return new Token(this)
}
// If we're in an ES6 environment, make parsers iterable
if (typeof Symbol !== "undefined")
pp$8[Symbol.iterator] = function() {
var this$1 = this;
return {
next: function () {
var token = this$1.getToken()
return {
done: token.type === tt.eof,
value: token
}
}
}
}
// Toggle strict mode. Re-reads the next number or string to please
// pedantic tests (`"use strict"; 010;` should fail).
pp$8.curContext = function() {
return this.context[this.context.length - 1]
}
// Read a single token, updating the parser object's token-related
// properties.
pp$8.nextToken = function() {
var curContext = this.curContext()
if (!curContext || !curContext.preserveSpace) this.skipSpace()
this.start = this.pos
if (this.options.locations) this.startLoc = this.curPosition()
if (this.pos >= this.input.length) return this.finishToken(tt.eof)
if (curContext.override) return curContext.override(this)
else this.readToken(this.fullCharCodeAtPos())
}
pp$8.readToken = function(code) {
// Identifier or keyword. '\uXXXX' sequences are allowed in
// identifiers, so '\' also dispatches to that.
if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
return this.readWord()
return this.getTokenFromCode(code)
}
pp$8.fullCharCodeAtPos = function() {
var code = this.input.charCodeAt(this.pos)
if (code <= 0xd7ff || code >= 0xe000) return code
var next = this.input.charCodeAt(this.pos + 1)
return (code << 10) + next - 0x35fdc00
}
pp$8.skipBlockComment = function() {
var this$1 = this;
var startLoc = this.options.onComment && this.curPosition()
var start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
this.pos = end + 2
if (this.options.locations) {
lineBreakG.lastIndex = start
var match
while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
++this$1.curLine
this$1.lineStart = match.index + match[0].length
}
}
if (this.options.onComment)
this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
startLoc, this.curPosition())
}
pp$8.skipLineComment = function(startSkip) {
var this$1 = this;
var start = this.pos
var startLoc = this.options.onComment && this.curPosition()
var ch = this.input.charCodeAt(this.pos += startSkip)
while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
++this$1.pos
ch = this$1.input.charCodeAt(this$1.pos)
}
if (this.options.onComment)
this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
startLoc, this.curPosition())
}
// Called at the start of the parse and after every token. Skips
// whitespace and comments, and.
pp$8.skipSpace = function() {
var this$1 = this;
loop: while (this.pos < this.input.length) {
var ch = this$1.input.charCodeAt(this$1.pos)
switch (ch) {
case 32: case 160: // ' '
++this$1.pos
break
case 13:
if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
++this$1.pos
}
case 10: case 8232: case 8233:
++this$1.pos
if (this$1.options.locations) {
++this$1.curLine
this$1.lineStart = this$1.pos
}
break
case 47: // '/'
switch (this$1.input.charCodeAt(this$1.pos + 1)) {
case 42: // '*'
this$1.skipBlockComment()
break
case 47:
this$1.skipLineComment(2)
break
default:
break loop
}
break
default:
if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
++this$1.pos
} else {
break loop
}
}
}
}
// Called at the end of every token. Sets `end`, `val`, and
// maintains `context` and `exprAllowed`, and skips the space after
// the token, so that the next one's `start` will point at the
// right position.
pp$8.finishToken = function(type, val) {
this.end = this.pos
if (this.options.locations) this.endLoc = this.curPosition()
var prevType = this.type
this.type = type
this.value = val
this.updateContext(prevType)
}
// ### Token reading
// This is the function that is called to fetch the next token. It
// is somewhat obscure, because it works in character codes rather
// than characters, and because operator parsing has been inlined
// into it.
//
// All in the name of speed.
//
pp$8.readToken_dot = function() {
var next = this.input.charCodeAt(this.pos + 1)
if (next >= 48 && next <= 57) return this.readNumber(true)
var next2 = this.input.charCodeAt(this.pos + 2)
if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
this.pos += 3
return this.finishToken(tt.ellipsis)
} else {
++this.pos
return this.finishToken(tt.dot)
}
}
pp$8.readToken_slash = function() { // '/'
var next = this.input.charCodeAt(this.pos + 1)
if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.slash, 1)
}
pp$8.readToken_mult_modulo_exp = function(code) { // '%*'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
var tokentype = code === 42 ? tt.star : tt.modulo
// exponentiation operator ** and **=
if (this.options.ecmaVersion >= 7 && next === 42) {
++size
tokentype = tt.starstar
next = this.input.charCodeAt(this.pos + 2)
}
if (next === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tokentype, size)
}
pp$8.readToken_pipe_amp = function(code) { // '|&'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
}
pp$8.readToken_caret = function() { // '^'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.bitwiseXOR, 1)
}
pp$8.readToken_plus_min = function(code) { // '+-'
var next = this.input.charCodeAt(this.pos + 1)
if (next === code) {
if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
// A `-->` line comment
this.skipLineComment(3)
this.skipSpace()
return this.nextToken()
}
return this.finishOp(tt.incDec, 2)
}
if (next === 61) return this.finishOp(tt.assign, 2)
return this.finishOp(tt.plusMin, 1)
}
pp$8.readToken_lt_gt = function(code) { // '<>'
var next = this.input.charCodeAt(this.pos + 1)
var size = 1
if (next === code) {
size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
return this.finishOp(tt.bitShift, size)
}
if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
this.input.charCodeAt(this.pos + 3) == 45) {
if (this.inModule) this.unexpected()
// `<!--`, an XML-style comment that should be interpreted as a line comment
this.skipLineComment(4)
this.skipSpace()
return this.nextToken()
}
if (next === 61) size = 2
return this.finishOp(tt.relational, size)
}
pp$8.readToken_eq_excl = function(code) { // '=!'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2)
if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
this.pos += 2
return this.finishToken(tt.arrow)
}
return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1)
}
pp$8.getTokenFromCode = function(code) {
switch (code) {
// The interpretation of a dot depends on whether it is followed
// by a digit or another two dots.
case 46: // '.'
return this.readToken_dot()
// Punctuation tokens.
case 40: ++this.pos; return this.finishToken(tt.parenL)
case 41: ++this.pos; return this.finishToken(tt.parenR)
case 59: ++this.pos; return this.finishToken(tt.semi)
case 44: ++this.pos; return this.finishToken(tt.comma)
case 91: ++this.pos; return this.finishToken(tt.bracketL)
case 93: ++this.pos; return this.finishToken(tt.bracketR)
case 123: ++this.pos; return this.finishToken(tt.braceL)
case 125: ++this.pos; return this.finishToken(tt.braceR)
case 58: ++this.pos; return this.finishToken(tt.colon)
case 63: ++this.pos; return this.finishToken(tt.question)
case 96: // '`'
if (this.options.ecmaVersion < 6) break
++this.pos
return this.finishToken(tt.backQuote)
case 48: // '0'
var next = this.input.charCodeAt(this.pos + 1)
if (next === 120 || next === 88) return this.readRadixNumber(16) // '0x', '0X' - hex number
if (this.options.ecmaVersion >= 6) {
if (next === 111 || next === 79) return this.readRadixNumber(8) // '0o', '0O' - octal number
if (next === 98 || next === 66) return this.readRadixNumber(2) // '0b', '0B' - binary number
}
// Anything else beginning with a digit is an integer, octal
// number, or float.
case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
return this.readNumber(false)
// Quotes produce strings.
case 34: case 39: // '"', "'"
return this.readString(code)
// Operators are parsed inline in tiny state machines. '=' (61) is
// often referred to. `finishOp` simply skips the amount of
// characters it is given as second argument, and returns a token
// of the type given by its first argument.
case 47: // '/'
return this.readToken_slash()
case 37: case 42: // '%*'
return this.readToken_mult_modulo_exp(code)
case 124: case 38: // '|&'
return this.readToken_pipe_amp(code)
case 94: // '^'
return this.readToken_caret()
case 43: case 45: // '+-'
return this.readToken_plus_min(code)
case 60: case 62: // '<>'
return this.readToken_lt_gt(code)
case 61: case 33: // '=!'
return this.readToken_eq_excl(code)
case 126: // '~'
return this.finishOp(tt.prefix, 1)
}
this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'")
}
pp$8.finishOp = function(type, size) {
var str = this.input.slice(this.pos, this.pos + size)
this.pos += size
return this.finishToken(type, str)
}
// Parse a regular expression. Some context-awareness is necessary,
// since a '/' inside a '[]' set does not end the expression.
function tryCreateRegexp(src, flags, throwErrorAt, parser) {
try {
return new RegExp(src, flags)
} catch (e) {
if (throwErrorAt !== undefined) {
if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message)
throw e
}
}
}
var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u")
pp$8.readRegexp = function() {
var this$1 = this;
var escaped, inClass, start = this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(start, "Unterminated regular expression")
var ch = this$1.input.charAt(this$1.pos)
if (lineBreak.test(ch)) this$1.raise(start, "Unterminated regular expression")
if (!escaped) {
if (ch === "[") inClass = true
else if (ch === "]" && inClass) inClass = false
else if (ch === "/" && !inClass) break
escaped = ch === "\\"
} else escaped = false
++this$1.pos
}
var content = this.input.slice(start, this.pos)
++this.pos
// Need to use `readWord1` because '\uXXXX' sequences are allowed
// here (don't ask).
var mods = this.readWord1()
var tmp = content, tmpFlags = ""
if (mods) {
var validFlags = /^[gim]*$/
if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/
if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag")
if (mods.indexOf("u") >= 0) {
if (regexpUnicodeSupport) {
tmpFlags = "u"
} else {
// Replace each astral symbol and every Unicode escape sequence that
// possibly represents an astral symbol or a paired surrogate with a
// single ASCII symbol to avoid throwing on regular expressions that
// are only valid in combination with the `/u` flag.
// Note: replacing with the ASCII symbol `x` might cause false
// negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
// perfectly valid pattern that is equivalent to `[a-b]`, but it would
// be replaced by `[x-b]` which throws an error.
tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
code = Number("0x" + code)
if (code > 0x10FFFF) this$1.raise(start + offset + 3, "Code point out of bounds")
return "x"
})
tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x")
tmpFlags = tmpFlags.replace("u", "")
}
}
}
// Detect invalid regular expressions.
var value = null
// Rhino's regular expression parser is flaky and throws uncatchable exceptions,
// so don't do detection if we are running under Rhino
if (!isRhino) {
tryCreateRegexp(tmp, tmpFlags, start, this)
// Get a regular expression object for this pattern-flag pair, or `null` in
// case the current environment doesn't support the flags it uses.
value = tryCreateRegexp(content, mods)
}
return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value})
}
// Read an integer in the given radix. Return null if zero digits
// were read, the integer value otherwise. When `len` is given, this
// will return `null` unless the integer has exactly `len` digits.
pp$8.readInt = function(radix, len) {
var this$1 = this;
var start = this.pos, total = 0
for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
var code = this$1.input.charCodeAt(this$1.pos), val
if (code >= 97) val = code - 97 + 10 // a
else if (code >= 65) val = code - 65 + 10 // A
else if (code >= 48 && code <= 57) val = code - 48 // 0-9
else val = Infinity
if (val >= radix) break
++this$1.pos
total = total * radix + val
}
if (this.pos === start || len != null && this.pos - start !== len) return null
return total
}
pp$8.readRadixNumber = function(radix) {
this.pos += 2 // 0x
var val = this.readInt(radix)
if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix)
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
return this.finishToken(tt.num, val)
}
// Read an integer, octal integer, or floating-point number.
pp$8.readNumber = function(startsWithDot) {
var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48
if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number")
if (octal && this.pos == start + 1) octal = false
var next = this.input.charCodeAt(this.pos)
if (next === 46 && !octal) { // '.'
++this.pos
this.readInt(10)
isFloat = true
next = this.input.charCodeAt(this.pos)
}
if ((next === 69 || next === 101) && !octal) { // 'eE'
next = this.input.charCodeAt(++this.pos)
if (next === 43 || next === 45) ++this.pos // '+-'
if (this.readInt(10) === null) this.raise(start, "Invalid number")
isFloat = true
}
if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number")
var str = this.input.slice(start, this.pos), val
if (isFloat) val = parseFloat(str)
else if (!octal || str.length === 1) val = parseInt(str, 10)
else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number")
else val = parseInt(str, 8)
return this.finishToken(tt.num, val)
}
// Read a string value, interpreting backslash-escapes.
pp$8.readCodePoint = function() {
var ch = this.input.charCodeAt(this.pos), code
if (ch === 123) {
if (this.options.ecmaVersion < 6) this.unexpected()
var codePos = ++this.pos
code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos)
++this.pos
if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds")
} else {
code = this.readHexChar(4)
}
return code
}
function codePointToString(code) {
// UTF-16 Decoding
if (code <= 0xFFFF) return String.fromCharCode(code)
code -= 0x10000
return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
}
pp$8.readString = function(quote) {
var this$1 = this;
var out = "", chunkStart = ++this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(this$1.start, "Unterminated string constant")
var ch = this$1.input.charCodeAt(this$1.pos)
if (ch === quote) break
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos)
out += this$1.readEscapedChar(false)
chunkStart = this$1.pos
} else {
if (isNewLine(ch)) this$1.raise(this$1.start, "Unterminated string constant")
++this$1.pos
}
}
out += this.input.slice(chunkStart, this.pos++)
return this.finishToken(tt.string, out)
}
// Reads template string tokens.
pp$8.readTmplToken = function() {
var this$1 = this;
var out = "", chunkStart = this.pos
for (;;) {
if (this$1.pos >= this$1.input.length) this$1.raise(this$1.start, "Unterminated template")
var ch = this$1.input.charCodeAt(this$1.pos)
if (ch === 96 || ch === 36 && this$1.input.charCodeAt(this$1.pos + 1) === 123) { // '`', '${'
if (this$1.pos === this$1.start && this$1.type === tt.template) {
if (ch === 36) {
this$1.pos += 2
return this$1.finishToken(tt.dollarBraceL)
} else {
++this$1.pos
return this$1.finishToken(tt.backQuote)
}
}
out += this$1.input.slice(chunkStart, this$1.pos)
return this$1.finishToken(tt.template, out)
}
if (ch === 92) { // '\'
out += this$1.input.slice(chunkStart, this$1.pos)
out += this$1.readEscapedChar(true)
chunkStart = this$1.pos
} else if (isNewLine(ch)) {
out += this$1.input.slice(chunkStart, this$1.pos)
++this$1.pos
switch (ch) {
case 13:
if (this$1.input.charCodeAt(this$1.pos) === 10) ++this$1.pos
case 10:
out += "\n"
break
default:
out += String.fromCharCode(ch)
break
}
if (this$1.options.locations) {
++this$1.curLine
this$1.lineStart = this$1.pos
}
chunkStart = this$1.pos
} else {
++this$1.pos
}
}
}
// Used to read escaped characters
pp$8.readEscapedChar = function(inTemplate) {
var ch = this.input.charCodeAt(++this.pos)
++this.pos
switch (ch) {
case 110: return "\n" // 'n' -> '\n'
case 114: return "\r" // 'r' -> '\r'
case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
case 117: return codePointToString(this.readCodePoint()) // 'u'
case 116: return "\t" // 't' -> '\t'
case 98: return "\b" // 'b' -> '\b'
case 118: return "\u000b" // 'v' -> '\u000b'
case 102: return "\f" // 'f' -> '\f'
case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos // '\r\n'
case 10: // ' \n'
if (this.options.locations) { this.lineStart = this.pos; ++this.curLine }
return ""
default:
if (ch >= 48 && ch <= 55) {
var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]
var octal = parseInt(octalStr, 8)
if (octal > 255) {
octalStr = octalStr.slice(0, -1)
octal = parseInt(octalStr, 8)
}
if (octalStr !== "0" && (this.strict || inTemplate)) {
this.raise(this.pos - 2, "Octal literal in strict mode")
}
this.pos += octalStr.length - 1
return String.fromCharCode(octal)
}
return String.fromCharCode(ch)
}
}
// Used to read character escape sequences ('\x', '\u', '\U').
pp$8.readHexChar = function(len) {
var codePos = this.pos
var n = this.readInt(16, len)
if (n === null) this.raise(codePos, "Bad character escape sequence")
return n
}
// Read an identifier, and return it as a string. Sets `this.containsEsc`
// to whether the word contained a '\u' escape.
//
// Incrementally adds only escaped chars, adding other chunks as-is
// as a micro-optimization.
pp$8.readWord1 = function() {
var this$1 = this;
this.containsEsc = false
var word = "", first = true, chunkStart = this.pos
var astral = this.options.ecmaVersion >= 6
while (this.pos < this.input.length) {
var ch = this$1.fullCharCodeAtPos()
if (isIdentifierChar(ch, astral)) {
this$1.pos += ch <= 0xffff ? 1 : 2
} else if (ch === 92) { // "\"
this$1.containsEsc = true
word += this$1.input.slice(chunkStart, this$1.pos)
var escStart = this$1.pos
if (this$1.input.charCodeAt(++this$1.pos) != 117) // "u"
this$1.raise(this$1.pos, "Expecting Unicode escape sequence \\uXXXX")
++this$1.pos
var esc = this$1.readCodePoint()
if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
this$1.raise(escStart, "Invalid Unicode escape")
word += codePointToString(esc)
chunkStart = this$1.pos
} else {
break
}
first = false
}
return word + this.input.slice(chunkStart, this.pos)
}
// Read an identifier or keyword token. Will check for reserved
// words when necessary.
pp$8.readWord = function() {
var word = this.readWord1()
var type = tt.name
if (this.keywords.test(word)) {
if (this.containsEsc) this.raiseRecoverable(this.start, "Escape sequence in keyword " + word)
type = keywordTypes[word]
}
return this.finishToken(type, word)
}
// Acorn is a tiny, fast JavaScript parser written in JavaScript.
//
// Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
// various contributors and released under an MIT license.
//
// Git repositories for Acorn are available at
//
// http://marijnhaverbeke.nl/git/acorn
// https://github.com/ternjs/acorn.git
//
// Please use the [github bug tracker][ghbt] to report issues.
//
// [ghbt]: https://github.com/ternjs/acorn/issues
//
// This file defines the main parser interface. The library also comes
// with a [error-tolerant parser][dammit] and an
// [abstract syntax tree walker][walk], defined in other files.
//
// [dammit]: acorn_loose.js
// [walk]: util/walk.js
var version = "5.0.3"
// The main exported interface (under `self.acorn` when in the
// browser) is a `parse` function that takes a code string and
// returns an abstract syntax tree as specified by [Mozilla parser
// API][api].
//
// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
function parse(input, options) {
return new Parser(options, input).parse()
}
// This function tries to parse a single expression at a given
// offset in a string. Useful for parsing mixed-language formats
// that embed JavaScript expressions.
function parseExpressionAt(input, pos, options) {
var p = new Parser(options, input, pos)
p.nextToken()
return p.parseExpression()
}
// Acorn is organized as a tokenizer and a recursive-descent parser.
// The `tokenizer` export provides an interface to the tokenizer.
function tokenizer(input, options) {
return new Parser(options, input)
}
// This is a terrible kludge to support the existing, pre-ES6
// interface where the loose parser module retroactively adds exports
// to this module.
// eslint-disable-line camelcase
function addLooseExports(parse, Parser, plugins) {
exports.parse_dammit = parse // eslint-disable-line camelcase
exports.LooseParser = Parser
exports.pluginsLoose = plugins
}
exports.version = version;
exports.parse = parse;
exports.parseExpressionAt = parseExpressionAt;
exports.tokenizer = tokenizer;
exports.addLooseExports = addLooseExports;
exports.Parser = Parser;
exports.plugins = plugins;
exports.defaultOptions = defaultOptions;
exports.Position = Position;
exports.SourceLocation = SourceLocation;
exports.getLineInfo = getLineInfo;
exports.Node = Node;
exports.TokenType = TokenType;
exports.tokTypes = tt;
exports.keywordTypes = keywordTypes;
exports.TokContext = TokContext;
exports.tokContexts = types;
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierStart = isIdentifierStart;
exports.Token = Token;
exports.isNewLine = isNewLine;
exports.lineBreak = lineBreak;
exports.lineBreakG = lineBreakG;
exports.nonASCIIwhitespace = nonASCIIwhitespace;
Object.defineProperty(exports, '__esModule', { value: true });
})));
/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function($) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return saveObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return loadGame; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__Alias_js__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__Company_js__ = __webpack_require__(17);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__Constants_js__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__engine_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Faction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__Gang_js__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__HacknetNode_js__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__Message_js__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__Player_js__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__Script_js__ = __webpack_require__(18);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__Server_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__Settings_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__StockMarket_js__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__utils_GameOptions_js__ = __webpack_require__(37);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_19__utils_decimal_js__);
/* SaveObject.js
* Defines the object used to save/load games
*/
let saveObject = new BitburnerSaveObject();
function BitburnerSaveObject() {
this.PlayerSave = "";
this.AllServersSave = "";
this.CompaniesSave = "";
this.FactionsSave = "";
this.SpecialServerIpsSave = "";
this.AliasesSave = "";
this.GlobalAliasesSave = "";
this.MessagesSave = "";
this.StockMarketSave = "";
this.SettingsSave = "";
this.VersionSave = "";
}
BitburnerSaveObject.prototype.saveGame = function() {
this.PlayerSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */]);
//Delete all logs from all running scripts
var TempAllServers = JSON.parse(JSON.stringify(__WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */]), __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
//var TempAllServers = jQuery.extend(true, {}, AllServers); //Deep copy
for (var ip in TempAllServers) {
var server = TempAllServers[ip];
if (server == null) {continue;}
for (var i = 0; i < server.runningScripts.length; ++i) {
var runningScriptObj = server.runningScripts[i];
runningScriptObj.logs.length = 0;
runningScriptObj.logs = [];
}
}
this.AllServersSave = JSON.stringify(TempAllServers);
this.CompaniesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_1__Company_js__["a" /* Companies */]);
this.FactionsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]);
this.SpecialServerIpsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["a" /* SpecialServerIps */]);
this.AliasesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["a" /* Aliases */]);
this.GlobalAliasesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["b" /* GlobalAliases */]);
this.MessagesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_7__Message_js__["b" /* Messages */]);
this.StockMarketSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["a" /* StockMarket */]);
this.SettingsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["a" /* Settings */]);
this.VersionSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].Version);
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].inGang()) {
this.AllGangsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_5__Gang_js__["a" /* AllGangs */]);
}
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
window.localStorage.setItem("bitburnerSave", saveString);
console.log("Game saved!");
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].createStatusText("Game saved!");
}
function loadGame(saveObj) {
if (!window.localStorage.getItem("bitburnerSave")) {
console.log("No save file to load");
return false;
}
var saveString = decodeURIComponent(escape(atob(window.localStorage.getItem("bitburnerSave"))));
saveObj = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
Object(__WEBPACK_IMPORTED_MODULE_8__Player_js__["b" /* loadPlayer */])(saveObj.PlayerSave);
Object(__WEBPACK_IMPORTED_MODULE_10__Server_js__["g" /* loadAllServers */])(saveObj.AllServersSave);
Object(__WEBPACK_IMPORTED_MODULE_1__Company_js__["i" /* loadCompanies */])(saveObj.CompaniesSave);
Object(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["i" /* loadFactions */])(saveObj.FactionsSave);
Object(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["d" /* loadSpecialServerIps */])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])(saveObj.AliasesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])(saveObj.GlobalAliasesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["e" /* loadMessages */])(saveObj.MessagesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])(saveObj.StockMarketSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["c" /* loadSettings */])(saveObj.SettingsSave);
} catch(e) {
console.log("ERROR: Failed to parse Settings. Re-initing default values");
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["b" /* initSettings */])();
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["b" /* initSettings */])();
}
if (saveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(saveObj.VersionSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN === null || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN === 0) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].setBitNodeNumber(1);
}
if (ver.startsWith("0.27.") || ver.startsWith("0.28.")) {
console.log("Evaluating changes needed for version compatibility");
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].augmentations.length > 0 || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].queuedAugmentations.length > 0 ||
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].sourceFiles.length > 0) {
//If you have already purchased an Aug...you are far enough in the game
//that everything should be available
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstFacInvRecvd = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstAugPurchased = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstJobRecvd = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstTimeTraveled = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstProgramAvailable = true;
} else {
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].factions.length > 0 || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].factionInvitations.length > 0) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstFacInvRecvd = true;
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].companyName !== "" || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].companyPosition !== "") {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstJobRecvd = true;
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].hacking_skill >= 25) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstScriptAvailable = true;
}
}
}
if (ver != __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].Version) {
createNewUpdateText();
}
} catch(e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_5__Gang_js__["d" /* loadAllGangs */])(saveObj.AllGangsSave);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
return true;
}
function loadImportedGame(saveObj, saveString) {
var tempSaveObj = null;
var tempPlayer = null;
var tempAllServers = null;
var tempCompanies = null;
var tempFactions = null;
var tempSpecialServerIps = null;
var tempAliases = null;
var tempGlobalAliases = null;
var tempMessages = null;
var tempStockMarket = null;
//Check to see if the imported save file can be parsed. If any
//errors are caught it will fail
try {
var decodedSaveString = decodeURIComponent(escape(atob(saveString)));
tempSaveObj = new BitburnerSaveObject();
tempSaveObj = JSON.parse(decodedSaveString, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
tempPlayer = JSON.parse(tempSaveObj.PlayerSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
//Parse Decimal.js objects
tempPlayer.money = new __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default.a(tempPlayer.money);
tempPlayer.total_money = new __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default.a(tempPlayer.total_money);
tempPlayer.lifetime_money = new __WEBPACK_IMPORTED_MODULE_19__utils_decimal_js___default.a(tempPlayer.lifetime_money);
tempAllServers = JSON.parse(tempSaveObj.AllServersSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
tempCompanies = JSON.parse(tempSaveObj.CompaniesSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
tempFactions = JSON.parse(tempSaveObj.FactionsSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
tempSpecialServerIps = JSON.parse(tempSaveObj.SpecialServerIpsSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
if (tempSaveObj.hasOwnProperty("AliasesSave")) {
try {
tempAliases = JSON.parse(tempSaveObj.AliasesSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
} catch(e) {
console.log("Parsing Aliases save failed: " + e);
tempAliases = {};
}
} else {
tempAliases = {};
}
if (tempSaveObj.hasOwnProperty("GlobalAliases")) {
try {
tempGlobalAliases = JSON.parse(tempSaveObj.AliasesSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
} catch(e) {
console.log("Parsing Global Aliases save failed: " + e);
tempGlobalAliases = {};
}
} else {
tempGlobalAliases = {};
}
if (tempSaveObj.hasOwnProperty("MessagesSave")) {
try {
tempMessages = JSON.parse(tempSaveObj.MessagesSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
} catch(e) {
console.log("Parsing Messages save failed: " + e);
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
tempStockMarket = JSON.parse(saveObj.StockMarketSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
} catch(e) {
console.log("Parsing StockMarket save failed: " + e);
tempStockMarket = {};
}
} else {
tempStockMarket = {};
}
if (tempSaveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(tempSaveObj.VersionSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
if (ver.startsWith("0.27.") || ver.startsWith("0.28.")) {
if (tempPlayer.bitNodeN == null || tempPlayer.bitNodeN == 0) {
tempPlayer.bitNodeN = 1;
}
if (tempPlayer.sourceFiles == null) {
tempPlayer.sourceFiles = [];
}
}
if (ver != __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].Version) {
//createNewUpdateText();
}
} catch(e) {
console.log("Parsing Version save failed: " + e);
//createNewUpdateText();
}
} else {
//createNewUpdateText();
}
if (tempPlayer.bitNodeN == 2 && tempPlayer.inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
AllGangs = JSON.parse(saveObj.AllGangsSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Error importing game: " + e.toString());
return false;
}
//Since the save file is valid, load everything for real
saveString = decodeURIComponent(escape(atob(saveString)));
saveObj = JSON.parse(saveString, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
Object(__WEBPACK_IMPORTED_MODULE_8__Player_js__["b" /* loadPlayer */])(saveObj.PlayerSave);
Object(__WEBPACK_IMPORTED_MODULE_10__Server_js__["g" /* loadAllServers */])(saveObj.AllServersSave);
Object(__WEBPACK_IMPORTED_MODULE_1__Company_js__["i" /* loadCompanies */])(saveObj.CompaniesSave);
Object(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["i" /* loadFactions */])(saveObj.FactionsSave);
Object(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["d" /* loadSpecialServerIps */])(saveObj.SpecialServerIpsSave);
if (saveObj.hasOwnProperty("AliasesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])(saveObj.AliasesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["c" /* loadAliases */])("");
}
if (saveObj.hasOwnProperty("GlobalAliasesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])(saveObj.GlobalAliasesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["d" /* loadGlobalAliases */])("");
}
if (saveObj.hasOwnProperty("MessagesSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["e" /* loadMessages */])(saveObj.MessagesSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_7__Message_js__["d" /* initMessages */])();
}
if (saveObj.hasOwnProperty("StockMarketSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])(saveObj.StockMarketSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])("");
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_13__StockMarket_js__["g" /* loadStockMarket */])("");
}
if (saveObj.hasOwnProperty("SettingsSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["c" /* loadSettings */])(saveObj.SettingsSave);
} catch(e) {
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["b" /* initSettings */])();
}
} else {
Object(__WEBPACK_IMPORTED_MODULE_11__Settings_js__["b" /* initSettings */])();
}
if (saveObj.hasOwnProperty("VersionSave")) {
try {
var ver = JSON.parse(saveObj.VersionSave, __WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */]);
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN == null || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN == 0) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].setBitNodeNumber(1);
}
if (ver.startsWith("0.27.") || ver.startsWith("0.28.")) {
console.log("Evaluating changes needed for version compatibility");
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].augmentations.length > 0 || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].queuedAugmentations.length > 0 ||
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].sourceFiles.length > 0) {
//If you have already purchased an Aug...you are far enough in the game
//that everything should be available
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstFacInvRecvd = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstAugPurchased = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstJobRecvd = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstTimeTraveled = true;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstProgramAvailable = true;
} else {
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].factions.length > 0 || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].factionInvitations.length > 0) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstFacInvRecvd = true;
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].companyName !== "" || __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].companyPosition !== "") {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstJobRecvd = true;
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].hacking_skill >= 25) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].firstScriptAvailable = true;
}
}
}
if (ver != __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].Version) {
createNewUpdateText();
}
} catch(e) {
createNewUpdateText();
}
} else {
createNewUpdateText();
}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].bitNodeN == 2 && __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].inGang() && saveObj.hasOwnProperty("AllGangsSave")) {
try {
Object(__WEBPACK_IMPORTED_MODULE_5__Gang_js__["d" /* loadAllGangs */])(saveObj.AllGangsSave);
} catch(e) {
console.log("ERROR: Failed to parse AllGangsSave: " + e);
}
}
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Imported game! I would suggest saving the game and then reloading the page " +
"to make sure everything runs smoothly");
Object(__WEBPACK_IMPORTED_MODULE_15__utils_GameOptions_js__["a" /* gameOptionsBoxClose */])();
//Re-start game
console.log("Importing game");
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].setDisplayElements(); //Sets variables for important DOM elements
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].init(); //Initialize buttons, work, etc.
__WEBPACK_IMPORTED_MODULE_1__Company_js__["d" /* CompanyPositions */].init();
//Calculate the number of cycles have elapsed while offline
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._lastUpdate = new Date().getTime();
var lastUpdate = __WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].lastUpdate;
var numCyclesOffline = Math.floor((__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._lastUpdate - lastUpdate) / __WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._idleSpeed);
/* Process offline progress */
var offlineProductionFromScripts = Object(__WEBPACK_IMPORTED_MODULE_9__Script_js__["e" /* loadAllRunningScripts */])(); //This also takes care of offline production for those scripts
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].isWorking) {
console.log("work() called in load() for " + numCyclesOffline * __WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._idleSpeed + " milliseconds");
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].WorkTypeFaction) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workForFaction(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].WorkTypeCreateProgram) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].createProgramWork(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].WorkTypeStudyClass) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].takeClass(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].WorkTypeCrime) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].commitCrime(numCyclesOffline);
} else if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workType == __WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].WorkTypeCompanyPartTime) {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].workPartTime(numCyclesOffline);
} else {
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].work(numCyclesOffline);
}
}
//Hacknet Nodes offline progress
var offlineProductionFromHacknetNodes = Object(__WEBPACK_IMPORTED_MODULE_6__HacknetNode_js__["c" /* processAllHacknetNodeEarnings */])(numCyclesOffline);
//Passive faction rep gain offline
Object(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["j" /* processPassiveFactionRepGain */])(numCyclesOffline);
//Update total playtime
var time = numCyclesOffline * __WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._idleSpeed;
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].totalPlaytime == null) {__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].totalPlaytime = 0;}
if (__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].playtimeSinceLastAug == null) {__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].playtimeSinceLastAug = 0;}
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].totalPlaytime += time;
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].playtimeSinceLastAug += time;
//Re-apply augmentations
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].reapplyAllAugmentations();
//Clear terminal
$("#terminal tr:not(:last)").remove();
__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */].lastUpdate = __WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"]._lastUpdate;
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].start(); //Run main game loop and Scripts loop
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("While you were offline, your scripts generated $" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineProductionFromScripts, 2) + " and your Hacknet Nodes generated $" +
Object(__WEBPACK_IMPORTED_MODULE_18__utils_StringHelperFunctions_js__["c" /* formatNumber */])(offlineProductionFromHacknetNodes, 2));
return true;
}
BitburnerSaveObject.prototype.exportGame = function() {
this.PlayerSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_8__Player_js__["a" /* Player */]);
this.AllServersSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_10__Server_js__["b" /* AllServers */]);
this.CompaniesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_1__Company_js__["a" /* Companies */]);
this.FactionsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_4__Faction_js__["b" /* Factions */]);
this.SpecialServerIpsSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_12__SpecialServerIps_js__["a" /* SpecialServerIps */]);
this.AliasesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["a" /* Aliases */]);
this.GlobalAliasesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_0__Alias_js__["b" /* GlobalAliases */]);
this.MessagesSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_7__Message_js__["b" /* Messages */]);
this.VersionSave = JSON.stringify(__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].Version);
var saveString = btoa(unescape(encodeURIComponent(JSON.stringify(this))));
var file = new Blob([saveString], {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 = "bitburnerSave.json";
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
BitburnerSaveObject.prototype.importGame = function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var fileSelector = Object(__WEBPACK_IMPORTED_MODULE_16__utils_HelperFunctions_js__["b" /* clearEventListeners */])("import-game-file-selector");
fileSelector.addEventListener("change", openImportFileHandler, false);
$("#import-game-file-selector").click();
} else {
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("ERR: Your browser does not support HTML5 File API. Cannot import.");
}
}
BitburnerSaveObject.prototype.deleteGame = function() {
if (window.localStorage.getItem("bitburnerSave")) {
window.localStorage.removeItem("bitburnerSave");
}
__WEBPACK_IMPORTED_MODULE_3__engine_js__["Engine"].createStatusText("Game deleted!");
}
function createNewUpdateText() {
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("New update!<br>" +
"Please report any bugs/issues through the github repository " +
"or the Bitburner subreddit (reddit.com/r/bitburner).<br><br>" +
__WEBPACK_IMPORTED_MODULE_2__Constants_js__["a" /* CONSTANTS */].LatestUpdate);
}
BitburnerSaveObject.prototype.toJSON = function() {
return Object(__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["b" /* Generic_toJSON */])("BitburnerSaveObject", this);
}
BitburnerSaveObject.fromJSON = function(value) {
return Object(__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["a" /* Generic_fromJSON */])(BitburnerSaveObject, value.data);
}
__WEBPACK_IMPORTED_MODULE_17__utils_JSONReviver_js__["c" /* Reviver */].constructors.BitburnerSaveObject = BitburnerSaveObject;
//Import game
function openImportFileHandler(evt) {
var file = evt.target.files[0];
if (!file) {
Object(__WEBPACK_IMPORTED_MODULE_14__utils_DialogBox_js__["a" /* dialogBoxCreate */])("Invalid file selected");
return;
}
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
loadImportedGame(saveObject, contents);
};
reader.readAsText(file);
}
/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(8)))
/***/ })
/******/ ]);